import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from '@angular/core';
import { FadeInTop } from "../../shared/animations/fade-in-top.decorator";
import { JsonApiService } from "app/core/api/json-api.service";
import { NotificationService } from "../../shared/utils/notification.service";
import { config } from '../../shared/smartadmin.config';
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { throwIfAlreadyLoaded } from 'app/core/guards/module-import-guard';
declare var $: any;
declare var BMap: any;
declare var echarts: any;
declare var toMapPoint: any;
declare var INFOBOX_AT_TOP;
@FadeInTop()
@Component({
	selector: 'sa-problem-analyse',
	templateUrl: './problem-analyse.component.html',
	styleUrls: ['./problem-analyse.css', './timeline.css']
})
export class ProblemAnalyseComponent implements OnInit {
	constructor(private jsonApiService: JsonApiService, private notificationService: NotificationService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			if (queryParams) {
				this.jumpData = queryParams;
			}
			// 订单监控跳转过来的数据
			if (common.getCookie('jumpFromOrderManagenment')) {
				this.jumpData = JSON.parse(common.getCookie('jumpFromOrderManagenment'));
				common.clearCookie('jumpFromOrderManagenment');
			}
		});
	}
	// select2左滑切换
	carIndexMsg: any = {
		allNums: 0,
		index: 1,
		status: false,
	}

	@Input() isShowTitle: any = true; //公司树标识Id
	@Input() dayNum: any = 1; // 时间默认初始化为前几天

	alertChartModelInfo: any = {};//echart异常警报信息模板信息
	versionChartModuleInfo: any = {};//echart固件升级信息模板信息
	coefChartModuleInfo: any = {};//echart系数设置信息模板信息
	companyChartModuleInfo: any = {};//echart厂区在线信息模板信息
	jumpData: any;
	isAllowPre: boolean = false;
	isAllowNext: boolean = false;

	myMap: any;
	apiType = '1'; //api接口
	lookSignal = true; //是否查看信号的条件
	loadometer = false; //是否查地磅信息的条件
	linetoMap = false; //是否选择地图联动的条件
	carSpeed = true; //是否查看速度的条件
	showModify = true; //显示修正数据
	questionRecord = true; //问题记录
	versionNumber = true;//版本号
	sensorChannel: boolean = false;//记录损坏传感器开关
	voltage: boolean = false;//设备电压信息开关
	deviceStatus: boolean = true;//设备状态开关
	versionMessage = {
		name: '',
		alarmType: '',
		versionString: '',
		runStatus: '',
		carUploadDate: '',
		gpsUploadDate: '',
		updateTime: '',
		isShowGPS: false,
	};//版本信息
	isGetRecord: any = { status: false };   //子组件是否请求问题记录数据

	recordTime = '';
	filterTime = '';
	filterTimeDefault: number;
	multiple = 1;
	magnificationArr = [1000, 5000, 10000, 100000]; //重量放大倍数
	startTime = '';
	endTime = '';
	startProblemTime = '';
	endProblemTime = '';
	problemStartTime = "";
	problemEndTime = "";
	companyId = '';
	selectedCompanyName = '';
	selectedCompanyId = '';


	inpSelect = ''; //点击折线获取时间 选中的输入框
	zeroBeforeDate = '';
	upStartDate = '';
	upEndDate = ''
	downStartDate = '';
	downEndDate = '';
	zeroAfterDate = '';

	carNumber = '';
	carList = [];
	companyList = [];
	companyNameArr = [];
	companyName = '';
	deviceId = ''; //设备ID
	startDate = ''; //开始时间
	endDate = ''; //结束时间
	waveWeight = '1.0';//波动范围

	myChart: any;
	allData = []; //echart图后台请求回来的数据
	passageData = []; //所有chart图折线的数组
	linetoMapData = []; //地图联动画轨迹数据
	loadometerData = []; //后台返回的地磅数据
	loadometerArr = []; //拼接成echart数组
	weightArr = []; //重量折线的数据
	carSpeedArr = []; //速度折线的数据
	passageName = []; //ad信号折线名
	passageArr = []; //ad信号数据
	voltageData: any = [];//设备电压数据,echart显示电压曲线
	voltageDataEchart: any = [];//设备电压数据,处理后数据

	errorRateArr = []; //记录误差率
	errorValueArr = []; //记录误差值       
	poundWeight = 0;//当前地磅重量
	errorRate: any = 0;//当前误差率
	errorValue = 0;//当前误差值
	signal16Arr = [];//16通道的数据
	ad16Value = 0;//对应地磅数据的16通道的信号误差值
	ad16Rate: any = 0;//对应地磅数据的16通道的信号值的误差率
	isRate16 = false;//是否计算16通道的误差率

	moveCanvasLayer: any; //轨迹移动添加点图层
	carMoveCanvasLayer: any;//移动折线对应地图添加点的图层,

	abnormalInfo;//地图上的异常警报窗口

	sensorTableData: any = [];//传感器损坏模块table数据
	startTime_sensor: string = '';//损坏传感器开始时间
	endTime_sensor: string = '';//损坏传感器结束时间
	sensorList: any = []; // 设备事件模块中的传感器通道问题数组
	otherData: any = {}; // 设备事件模块中的其他数据 弥补之前的接口数据不足
	renewalInfo: any = ''; // 车辆的续费信息
	sensorArr: any = [{
		id: 1,
		text: '通道1',
		checked: false
	}, {
		id: 2,
		text: '通道2',
		checked: false
	}, {
		id: 3,
		text: '通道3',
		checked: false
	}, {
		id: 4,
		text: '通道4',
		checked: false
	}, {
		id: 5,
		text: '通道5',
		checked: false
	}, {
		id: 6,
		text: '通道6',
		checked: false
	}, {
		id: 7,
		text: '通道7',
		checked: false
	}, {
		id: 8,
		text: '通道8',
		checked: false
	}, {
		id: 9,
		text: '通道9',
		checked: false
	}, {
		id: 10,
		text: '通道10',
		checked: false
	}, {
		id: 11,
		text: '通道11',
		checked: false
	}, {
		id: 12,
		text: '通道12',
		checked: false
	}, {
		id: 13,
		text: '通道13',
		checked: false
	}, {
		id: 14,
		text: '通道14',
		checked: false
	}, {
		id: 15,
		text: '通道15',
		checked: false
	}, {
		id: 16,
		text: '通道16',
		checked: false
	}]
	private isMoveFlag: boolean = true;		//防抖节流，控制mousemove触发频率
	//	powerOffAlertList:any = [];//断电异常数据集合

	//重量y轴线
	yAxiWeight: any = {
		show: true,
		name: '重量',
		type: 'value',
		position: 'left',
		min: undefined,
		max: undefined,
		offset: undefined,
		axisLine: {
			lineStyle: {
				color: 'gray'
			}
		},
		axisLabel: {
			formatter: '{value}'
		}
	}

	//信号y轴线
	yAxiSignal: any = {
		show: false,
		name: '信号',
		splitLine: {
			show: false
		},
		type: 'value',
		position: 'right',
		min: undefined,
		max: undefined,
		offset: undefined,
		axisLine: {
			lineStyle: {
				color: '#5c427c'
			}
		},
		axisLabel: {
			formatter: '{value}'
		}
	}

	//速度y轴线
	yAxiSpeed: any = {
		show: false,
		name: '速度 KM/H',
		splitLine: {
			show: false
		},
		type: 'value',
		min: undefined,
		max: undefined,
		offset: 60,
		position: 'right',
		axisLine: {
			lineStyle: {
				color: '#5793f3'
			}
		},
		axisLabel: {
			formatter: '{value}'
		}
	}

	//	指定图表的配置项和数据
	echartOption = {
		//		title: {
		//			left: '2%',
		//			top: '0px',
		//			text: '车载重量'
		//		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross' //十字星	
			},
			formatter: function (params) {
				if (this.linetoMap) {
					var paramIndex = params[0].dataIndex;
					var pointObj = this.linetoMapData[paramIndex];
					if (!pointObj || pointObj.x == '' || pointObj.x == '0') {
						return;
					}
					this.lineMoveCarPoint(pointObj)
				}

				if (!window.event) {
					return;
				}
				if (!window.event.type) {
					return;
				}
				var triggerType = window.event.type; //触发类型
				var str = this.inpSelect;
				if (triggerType == 'click') {
					this.recordTime = params[0].name;
					if (!str) return;
					this[str] = params[0].name;
					if (str == 'downEndDate' || str == 'upStartDate') {
						if (startime1 == '' || endTime1 == '') {
							return;
						}
						if (this.loadometerData.length > 0) {
							var startime1 = this.changeTime(this.upStartDate);
							var endTime1 = this.changeTime(this.downEndDate);
							for (var j = 0; j < this.loadometerData.length; j++) {
								var contrastTime = this.changeTime(this.loadometerData[j].date);
								if (startime1 < contrastTime && contrastTime <= endTime1) {
									$('#weight').val(Math.floor(+this.loadometerData[j].weight * 10) / 10);
									break;
								}
							}
						}
					}
				}
				var res = '';
				var len = params.length;
				for (var i = 0; i < len; i++) {
					res = res + params[i].marker + params[i].seriesName + ':' + params[i].data + '</br>'
				}
				return res;

			}.bind(this)
		},
		grid: {
			left: '54px',
			right: '100px',
			top: '80px'
		},
		toolbox: {
			feature: {
				dataView: {
					show: false,
					readOnly: false
				},
				restore: {
					show: false
				},
				saveAsImage: {
					show: false
				}
			}
		},
		legend: {
			selected: {},
		},
		xAxis: {
			type: 'category',
			boundaryGap: false,
			data: []
		},
		yAxis: [this.yAxiWeight],

		dataZoom: [{

			realtime: true
		}, {
			type: 'inside',
			realtime: true,
		}],
		series: [{
			name: '重量',
			type: 'line',
			//			itemStyle: {
			//				color: 'red'
			//			},
			data: []
		}]

	};

	isDisable = true;
	coefficientList = [];
	coefCarStatus = 'offline';
	coefCarNumber = '';

	proTypeOptions = [];//存储问题记录分类选项描述
	proSlectedItem: any;//记录选中一类时的数据,渲染页面选项
	proTypeParams: any = {		//存储用户操作选择的数据
		problemType: '',			//问题类型
		problemClass: '',		//问题分类
		phenomenon: '',			//问题现象
		repairGuide: '',			//维修指导
		repairWay: '',			//维修方式
		pheDescribe: '',			//现象描述
	}
	seneorPhenlist = [];

	hideOrshowline = [];
	legendSleced: any = {};
	carIndexMess = {
		allNums: 0,
		index: 1,
		status: false,
	}
	/**
	 * 通道 安装位置
	 */

	sensorAxleFront: any = [] //通道前
	sensorAxleAfter: any = [] //通道后
	installArray: any = [] //安装位置
	checkChannel: any = []//选中通道数组
	ChannelLen: any = ''//原始轴的个数
	// gps选项
	gpsOptions = allSelectOptionsObj.gpsOptions;
	// gsm选项
	gsmOptions = allSelectOptionsObj.gsmOptions;
	haveRepaireObj: any = {} // 已维修返回的对象  system/getDeviceBaseInfoByDeviceId.html这个接口请求后存在对象中方便不同的方法使用这个对象
	message(data) {
		this.notificationService.smallBox({
			content: data,
			timeout: 3000
		});
	}
	confirm_message(message) {
		return new Promise(function (resolve, reject) {
			this.notificationService.smartMessageBox({
				title: "提示",
				content: message,
				buttons: '[确认][取消]'
			}, (ButtonPressed) => {
				if (ButtonPressed === "确认") {
					resolve();
				}
				if (ButtonPressed === "取消") {
					this.notificationService.smallBox({
						content: "操作取消",
						timeout: 3000
					});
					return;
				}

			});
		}.bind(this))
	}
	searchTimer: any;
	//设备ID自己更改时候 公司数据以及车辆数据也相应的更新
	devicedChange(e) {
		let that = this;
		var key = e.target.value;

		this.searchTimer && clearTimeout(this.searchTimer);
		this.searchTimer = setTimeout(() => {
			if (that.selectRowData.deviceId || that.carNumber) {
				if (that.selectRowData.deviceId != key) {

					$('#companyTree .s_del_icon').click();

					that.deviceId = key;
					that.selectRowData.deviceId = key;
				}
			}
		}, 1000);
	}
	//公司选中回调
	companySelected(val) {
		this.deviceId = val.deviceId;
		this.carNumber = val.carNumber;
		this.selectedCompanyId = val.companyId;
		this.selectedCompanyName = val.companyName;
		this.selectRowData.companyId = val.companyId;
		this.selectRowData.companyName = val.companyName;
		this.selectRowData.deviceId = val.deviceId;
		this.selectRowData.carNumber = val.carNumber;
		if (val.carNumber && this.carNumberWeight) {
			this.carNumberWeight = '';
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$('#loadometerSelect').val("");
			$("#select2-loadometerSelect-container").empty();
			$("#select2-loadometerSelect-container").attr("title", "");
			$("#select2-loadometerSelect-container").prepend(str);
			this.carIndexMsg.status = false;	//清空磅单数量
		}
		if (!this.selectedCompanyId) {
			var selectObj = $("#loadometerSelect");
			this.clearSelect2(selectObj); //清除Select中的数据
			this.carIndexMsg.status = false;	//清空磅单数量			
		} else {
			if (val.companyClickFlag) {
				this.queryCarListByCompanyId();
			}
		}
		//组件车辆上下键事件生效,清除父级冲突的上下键盘事件
		if (val.clearKeyCodeEvent && val.carNumber) {
			document.body.onkeydown = null;
		}
		//组件enter监听
		if (val.enterEventFlag) {
			this.showCheart();
		}

		//清空算法问题
		for (let lis of this.algorithmQuestionList) {
			lis.selected = false;
		}
	}
	//获取传感器参数
	getVersionMessage() {
		if (!this.versionNumber) return;
		if (!this.deviceId) return;
		this.versionMessage = {
			name: '',
			alarmType: '',
			versionString: '',
			runStatus: '',
			carUploadDate: '',
			gpsUploadDate: '',
			updateTime: '',
			isShowGPS: false,
		}
		let reqdata = 'deviceId=' + this.deviceId;
		this.hideOrshowline = [];
		this.jsonApiService.http("system/getRealTimeData.html", reqdata).subscribe(result => {
			if (!result.success) return;
			this.versionMessage.name = result.data.version;
			this.versionMessage.runStatus = result.data.runStatus;
			this.versionMessage.carUploadDate = result.data.carUploadDate;
			this.versionMessage.gpsUploadDate = result.data.gpsUploadDate;
			this.versionMessage.updateTime = result.data.updateTime;
			if (result.data.alarmType == '1' || result.data.alarmType == '2') {
				this.versionMessage.alarmType = '[断电中]'
			} else if (result.data.alarmType == '0' || !result.data.alarmType) {
				this.versionMessage.alarmType = '[未知原因]'
			} else if (result.data.alarmType == '3') {
				this.versionMessage.alarmType = '[异常断电]'
			} else if (result.data.alarmType == '4' && result.data.runStatus == '1') {
				this.versionMessage.alarmType = '[回传数据]'
			}
			if (this.versionMessage.carUploadDate && this.versionMessage.gpsUploadDate) {
				let abs = Math.abs(common.mmsstoTimestamp(this.versionMessage.carUploadDate) - common.mmsstoTimestamp(this.versionMessage.gpsUploadDate));
				abs >= 30 * 60 * 1000 ? this.versionMessage.isShowGPS = true : this.versionMessage.isShowGPS = false;
			}
			let coefArr = [];
			if (!result.data.coef) return
			for (let i = 0; i < result.data.coef.length; i++) {
				let item = result.data.coef[i];
				if (item) {
					let vname = '通道' + (i + 1);
					coefArr.push(vname + ':' + item);
					this.hideOrshowline.push(vname)
				}
			}
			let resultString = '';
			for (let _i = 0; _i < coefArr.length; _i++) {
				if (_i < coefArr.length - 1) {
					resultString += coefArr[_i] + ',';
				} else {
					resultString += coefArr[_i]
				}
			}
			this.versionMessage.versionString = resultString;

			// 初始化传感器问题和Gps问题
			this.initSeneorGps();
		})
	}
	keyCodeEvent() {
		let that = this;
		document.body.onkeydown = null;
		document.onkeydown = null;
		document.body.onkeydown = function (event) {
			var e = event || window.event || arguments.callee.caller.arguments[0];
			if (e && this.loadometer) {		//地磅数据勾选情况下才触发keydown事件
				if (e.keyCode == 38) {
					this.nextCarLoad('pre');
					return false;
				}
				if (e.keyCode == 40) {
					this.nextCarLoad('next');
					return false;
				}
				if (e.keyCode == 13) {
					this.showCheart();
					return false;
				}
			}
		}.bind(this)
	}
	ngOnInit() {
		// 榜单数据
		let that = this;
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				that.selectLoadometer(); //初始化select 2 榜单
			});
		});
		if (this.inputParam.length == 0) { this.querySensor(); }// 请求传感器列表接口
		this.getGpsInfo(); //请求天线配置接口
		this.tableMove();
		this.initProTypeOptions();
		this.initCoefficientList();
		this.initDate().then(() => {
			if (this.jumpData.deviceId) {
				this.deviceId = this.jumpData.deviceId;
				this.carNumber = this.jumpData.carNumber;
				this.startTime = this.jumpData.startDate;
				this.endTime = this.jumpData.endDate;
				$('#datetimepicker1').val(this.startTime);
				$('#datetimepicker2').val(this.endTime);
				setTimeout(function () {
					$('#carNumberSelect2').val(this.deviceId).trigger('change');
					var str = $("<span class='select2-selection__rendered'>" + this.carNumber + "</span>");
					$('#carNumberSelect2').val("");
					$("#select2-carNumberSelect2-container").empty();
					$("#select2-carNumberSelect2-container").attr("title", "");
					$("#select2-carNumberSelect2-container").prepend(str);
				}.bind(this), 100);
				this.showCheart();
			}
		});
		//初始化创建一个空的信息窗口
		var content = '<div class="massageDiv">' +
			'<p class="p1">（KM/H）</span></p>' +
			'<div class="content">' +
			'<div class="contentImage"><div class="contentImage-img"><img src="assets/img/trackImage/positionInfo4.png"></div></div>' +
			'<div class="contentText">' +
			'<p><span class="leftSpan">经度：</span><span class="rightSpan"></span></p>' +
			'<p><span class="leftSpan">纬度：</span><span class="rightSpan"></span></p>' +
			'<p><span class="leftSpan">载重量：</span><span class="rightSpan"></span></p>' +
			'<p><span class="leftSpan">更新时间：</span><span class="rightSpan"></span></p>' +
			'</div></div>' +
			'</div>';
		var opts = {
			width: 400,
			heigth: 300,
		};
		var infoWindow = new BMap.InfoWindow(content, opts);
		this.myChart = echarts.init(document.getElementById('chart'));
		this.initChart();
		window.onresize = function () {
			setTimeout(() => {
				that.myChart.resize()
			}, 120)
		}
		this.myChart.on('click', function (params) {
			if (params.componentType === 'markPoint') {
				if (params.name == "离线警报" || params.name == "断电警报") {
					if (this.linetoMap) {
						var pointObj = params.data;
						if (!pointObj || pointObj.lng == '' || pointObj.lat == '0') {
							this.message('经纬度异常');
							return;
						}
						this.createAbnormalInfo(pointObj)
					}
				}
			} else {
				var pointObj = that.allData[params.dataIndex];
				if (pointObj == undefined) {
					return;
				}
				var geturl = config.BaseURL;
				pointObj.companyName = that.selectedCompanyName;
				if (that.mapClick) {
					common.createInfoBox(that.myMap, pointObj, geturl);
					that.mapClick = false;
					setTimeout(() => {
						that.mapClick = true;
					}, 300);
				}
			}
		}.bind(this))
		let map = new BMap.Map('allmap', { enableMapClick: false }); //创建地图实例
		let point = new BMap.Point(116.404, 39.915); //创建点坐标
		map.centerAndZoom(point, 15); //初始化地图，设置中心点坐标和地图级别
		map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
		map.disableDoubleClickZoom();//禁用双击放大
		this.myMap = map;
		// 车辆选择框发生改变触发
		$('#carNumberSelect2').on('change', (e) => {
			// var data = e.params.data;
			if (e.target.value) {
				this.deviceId = e.target.value
				this.initSeneorGps()
			}
		});

		// $(document).mouseup(function(e){
		// 	  var _con = $('.holdImg');   // 设置目标区域
		// 	  var _holdOpenImg = $('.holdOpenImg');
		// 	  if(_holdOpenImg.is(e.target)){
		// 		if(!_con.is(e.target) && _con.has(e.target).length === 0){ // Mark 1
		// 			that.isHold = true
		// 		}
		// 	  }

		// });

		// this.dragDrop() // 拖拽工具箱
	}
	ngOnDestroy() {
		document.onclick = null;
		document.onkeydown = null;
		document.body.onkeydown = null;
		window.onresize = null;
	}
	//初始化时间
	initDate() {
		let that = this;
		return new Promise(function (resolve, error) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
				System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
					$("#datetimepicker1").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.startTime = time
						$("#datetimepicker2").datetimepicker("setStartDate", time);
						$("#datetimepicker1").change();
						if (that.selectedCompanyId && that.loadometer) {
							that.queryCarListByCompanyId();
						}
					});
					$("#datetimepicker2").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.endTime = time;
						$("#datetimepicker1").datetimepicker("setEndDate", time);
						$("#datetimepicker2").change();
						if (that.selectedCompanyId && that.loadometer) {
							that.queryCarListByCompanyId();
						}
					});
					$("#datetimepicker3").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.startProblemTime = time
						$("#datetimepicker4").datetimepicker("setStartDate", time);
						$("#datetimepicker3").change();

					});
					$("#datetimepicker4").datetimepicker({ //时间插件
						format: "yyyy-mm-dd hh:ii:ss",
						language: "zh-CN",
						autoclose: true,
					}).on("changeDate", function (e) {
						var date = e.date;
						var time = common.getTimeMmss(date);
						that.endProblemTime = time;
						$("#datetimepicker3").datetimepicker("setEndDate", time);
						$("#datetimepicker4").change();
					});
					var date = new Date();
					let time1 = common.getTimeMmss(date);
					$("#datetimepicker2").val(time1); //当前时间
					$("#datetimepicker4").val(time1); //当前时间
					that.endTime = time1;
					that.endProblemTime = time1;
					date.setDate(date.getDate() - that.dayNum); //设置前一天
					let time2 = common.getTimeMmss(date);
					$("#datetimepicker1").val(time2);
					$("#datetimepicker3").val(time2);
					that.startTime = time2;
					that.startProblemTime = time2;
					resolve();
				})
			})
		});
	}
	//删除所选日期
	del_date() {
		$('#datetimepicker1').val('');
		$('#datetimepicker2').val('');
		this.startTime = '';
		this.endTime = '';
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	del_problemdate() {
		$('#datetimepicker3').val('');
		$('#datetimepicker4').val('');
		this.startProblemTime = '';
		this.endProblemTime = '';
		$("#datetimepicker3").datetimepicker("setStartDate", null);
		$("#datetimepicker4").datetimepicker("setEndDate", null);
	}
	//初始化echart图
	initChart() {
		this.allData = []; //echart图后台请求回来的数据
		this.passageData = []; //所有chart图折线的数组
		this.linetoMapData = []; //地图联动画轨迹数据
		this.loadometerData = []; //后台返回的地磅数据
		this.loadometerArr = []; //拼接成echart数组
		this.weightArr = []; //重量折线的数据
		this.carSpeedArr = [];//速度折线的数据
		this.passageName = [];//ad信号折线名
		this.passageArr = [];//ad信号数据
		this.echartOption.xAxis.data = [];
		this.echartOption.series = [];
		this.myChart.setOption(this.echartOption, true);
	}

	// 监听设备id变化
	deviceIdChange() {
		console.log(this.deviceId)
	}


	//百度地图绘画路线,不带方向箭头,当前版本不用该函数
	drawTrack(map, param) {
		var pointArr = param;
		map.clearOverlays();

		var linkPoint = [];
		var linkPoint = []; //拼接线的折点

		for (var i = 0; i < pointArr.length; i++) {
			//    转换成百度坐标
			var mapPoint = toMapPoint(pointArr[i]);
			if (mapPoint) {
				linkPoint.push(new BMap.Point(mapPoint.lng, mapPoint.lat));
			}
		}
		var polyline = new BMap.Polyline(linkPoint, {
			strokeColor: "#4169e1",
			strokeWeight: 6,
			strokeOpacity: 0.9
		}); //创建折线
		map.addOverlay(polyline);
		var starPoint = new BMap.Point(pointArr[0].lng, pointArr[0].lat);
		var endPoint = new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat);
		var opts = {
			position: starPoint, // 指定起点所在的地理位置
			offset: new BMap.Size(0, 0) //文本偏移量
		};
		var endOpts = {
			position: endPoint, // 指定终点点所在的地理位置
			offset: new BMap.Size(0, 0) //文本偏移量
		};
		var label = new BMap.Label('起点', opts); // 创建文本内容
		var endLabel = new BMap.Label('终点', endOpts); // 创建文本内容
		label.setStyle({
			color: "red",
			fontSize: "12px",
			height: "20px",
			padding: "0px 30px 0 2px",
			margin: 0,
			lineHeight: "20px",
			fontFamily: "微软雅黑"
		});
		endLabel.setStyle({
			color: "red",
			fontSize: "12px",
			height: "20px",
			padding: "0px 30px 0 2px",
			margin: 0,
			lineHeight: "20px",
			fontFamily: "微软雅黑"
		});
		map.addOverlay(label);
		map.addOverlay(endLabel);
		setTimeout(function () {
			map.centerAndZoom(new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat), 10);
		}, 10);
	}

	// * 时间格式检查
	checkDateTime(str) {
		var reg = /^(\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/;
		var r = str.match(reg);
		if (r == null) return false;
		r[2] = r[2] - 1;
		var d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]);
		if (d.getFullYear() != r[1]) return false;
		if (d.getMonth() != r[2]) return false;
		if (d.getDate() != r[3]) return false;
		if (d.getHours() != r[4]) return false;
		if (d.getMinutes() != r[5]) return false;
		if (d.getSeconds() != r[6]) return false;
		return true;
	}
	//撤回
	recall() {
		var deviceId = this.deviceId;
		var zeroBeforeDate = $("#zeroBeforeDate").val();
		var zeroAfterDate = $("#zeroAfterDate").val();
		if (deviceId == "") {
			this.message('请选择车牌号');
			return;
		}
		if (!this.checkDateTime(zeroBeforeDate)) {
			this.message('上货前置零起始时间格式不正确或为空');
			return;
		}
		if (!this.checkDateTime(zeroAfterDate)) {
			this.message('卸货后置零结束间格式不正确或为空');
			return;
		}
		let that = this;
		this.confirm_message('是否确认所有时间段没问题,然后开始撤销数据吗').then(() => {
			$.ajax({
				type: "POST",
				url: config.BaseURL + "system/recall.html",
				data: {
					"deviceId": deviceId,
					"upStartDate": zeroBeforeDate,
					"downEndDate": zeroAfterDate
				},
				xhrFields: {
					withCredentials: true
				},
				dataType: "json",
				success: function (result) {

					that.message(result.message)
				},
				error: function (errorMsg) {

					that.message('网络错误,请联系管理员')
				}
			});
		})
	}
	//判断时间是否在问题记录时间区间内
	timeInProblemStartEnd() {
		let result = true;
		if (!this.startTime_problem || !this.endTime_problem) {
			this.jsonApiService.message('问题记录起始时间不能为空');
			result = false;
			return result;
		}
		let stNum_pb = common.mmsstoTimestamp(this.startTime_problem);
		let etNum_pb = common.mmsstoTimestamp(this.endTime_problem);
		if (!stNum_pb || !etNum_pb) {
			this.jsonApiService.message('问题记录起始时间格式不正确');
			result = false;
			return result;
		}

		let checkArr = [
			{ name: '上货前置零起始时间', time: this.zeroBeforeDate },
			{ name: '上货点起始时间', time: this.upStartDate },
			{ name: '上货点结束时间', time: this.upEndDate },
			{ name: '卸货点起始时间', time: this.downStartDate },
			{ name: '卸货点结束时间', time: this.downEndDate },
			{ name: '卸货后置零结束时间', time: this.zeroAfterDate },
		]

		for (let item of checkArr) {
			if (item.time) {
				let _tn = common.mmsstoTimestamp(item.time);
				if (_tn < stNum_pb || _tn > etNum_pb) {
					this.jsonApiService.message(item.name + '需要在问题起始结束时间内');
					result = false;
					break;
				}
			}

		}
		return result;

	}


	//数据优化提交
	makeData() {
		let exceptionType: any, proType: any;
		if (!this.proTypeParams.problemType || !this.proTypeParams.problemClass) {
			this.jsonApiService.message('请选择问题分类');
			return;
		}
		if (this.proTypeParams.problemType) {
			let operaParam = this.getSelectedVAL();
			proType = (+this.proTypeParams.problemType + 1) + '0' + (+this.proTypeParams.problemClass + 1);
			if (operaParam.problemClassStr == '其他') {
				proType = (+this.proTypeParams.problemType + 1) + '00';
			}
			exceptionType = +this.proTypeParams.problemType + 1;
		}
		var deviceId = this.deviceId;
		var upStartDate = $("#upStartDate").val();
		var upEndDate = $("#upEndDate").val();
		var weight = $("#weight").val();
		var downStartDate = $("#downStartDate").val();
		var downEndDate = $("#downEndDate").val();
		var zeroBeforeDate = $("#zeroBeforeDate").val();
		var zeroAfterDate = $("#zeroAfterDate").val();
		var startWeight = $("#startWeight").val();
		var endWeight = $("#endWeight").val();
		if (deviceId == "") {
			this.message('请选择车牌号');
			return;
		}
		var isSumit = this.isAllDateTime();
		if (!isSumit) {
			return;
		}
		var isWave = $("#isWave").prop('checked'); //返回 true/false
		var isDiagonal = $("#isDiagonal").prop('checked'); //上卸货曲线,返回 true/false
		let that = this;

		if (zeroBeforeDate && upStartDate) {
			if (common.mmsstoTimestamp(zeroBeforeDate) - common.mmsstoTimestamp(upStartDate) > 0) {
				this.jsonApiService.message('上货前置零时间不能大于上货时间');
				return;
			}
		}
		if (upStartDate && upEndDate) {
			if (common.mmsstoTimestamp(upStartDate) - common.mmsstoTimestamp(upEndDate) > 0) {
				this.jsonApiService.message('上货开始时间不能大于上货结束时间');
				return;
			}
		}
		if (upEndDate && downStartDate) {
			if (common.mmsstoTimestamp(upEndDate) - common.mmsstoTimestamp(downStartDate) > 0) {
				this.jsonApiService.message('上货结束时间不能大于卸货开始时间');
				return;
			}
		}
		if (downStartDate && downEndDate) {
			if (common.mmsstoTimestamp(downStartDate) - common.mmsstoTimestamp(downEndDate) > 0) {
				this.jsonApiService.message('卸货开始时间不能大于卸货结束时间');
				return;
			}
		}
		if (downEndDate && zeroAfterDate) {
			if (common.mmsstoTimestamp(downEndDate) - common.mmsstoTimestamp(zeroAfterDate) > 0) {
				this.jsonApiService.message('卸货结束时间不能大于卸货后置零结束时间');
				return;
			}
		}
		let isTime = this.timeInProblemStartEnd();
		if (!isTime) return;
		this.confirm_message('是否确认所有时间段没问题，然后开始进行数据替换吗？').then(() => {
			layer.load();
			$.ajax({
				type: "POST",
				url: config.BaseURL + "system/makedata.html",
				xhrFields: {
					withCredentials: true
				},
				data: {
					"deviceId": deviceId,
					"upStartDate": upStartDate,
					"upEndDate": upEndDate,
					"weight": weight,
					"downStartDate": downStartDate,
					"downEndDate": downEndDate,
					"isWave": isWave,
					"zeroBeforeDate": zeroBeforeDate,
					"zeroAfterDate": zeroAfterDate,
					"isDiagonal": isDiagonal,
					"startWeight": startWeight,
					"endWeight": endWeight,
					"waveWeight": that.waveWeight,
					"exceptionType": exceptionType,
					"programType": proType,
					"orderId": '',
				},
				dataType: "json",
				success: function (result) {

					that.message(result.message);

					layer.closeAll('loading');
				},
				error: function (errorMsg) {

					that.message('网络错误请联系管理员');

				}
			});

		})

	}
	//监听所有填写了的时间输入框的值必须为时间格式.
	isAllDateTime() {
		var result = true;
		//		var isAllNull=true;//必要的2组时间是否为空,都为空的时候阻止掉
		//		var upStartDate=$('#upStartDate').val();//上货点起始时间
		//		var upEndDate=$('#upEndDate').val();//上货点结束时间
		//		var downStartDate=$('#downStartDate').val();//卸货点起始时间
		//		var downEndDate=$('#downEndDate').val();//卸货点结束时间
		var weight = $('#weight').val();
		if (weight == '') {
			result = false;
			this.message('请输入重量值...');
			return result;
		}
		//		if(this.checkDateTime(upStartDate)&&this.checkDateTime(upEndDate)){
		//			isAllNull=false;
		//		}
		//		if(this.checkDateTime(downStartDate)&&this.checkDateTime(downEndDate)){
		//			isAllNull=false;
		//		}
		//		if(isAllNull){
		//			//2组时间都为空
		//			this.message('上货点起始时间+上货点结束时间 或者卸货点起始时间+卸货点结束时间 必须要正确填写一组');
		//			result=false;
		//			return result;
		//		}
		//		else{
		//有一组时间填写要求正确,校验是否正确填写时间格式
		var messageVal = '';
		var that = this;
		$('.getChartTime').each(function (index) {

			var indexVal = $(this).val();
			if (indexVal !== '') {
				if (!that.checkDateTime(indexVal)) {
					var mes = $(this).attr('placeholder').split('（')[0];
					messageVal = messageVal + mes + ' ';
					result = false;
				}
			}
		})
		if (messageVal !== '') {
			this.message(messageVal + '格式不正确');
		}
		return result;
		//		}	
	}
	//记录上卸货点
	recordTransportData() {
		var deviceId = this.deviceId;
		var upStartDate = $("#upStartDate").val();
		var upEndDate = $("#upEndDate").val();
		var weight = $("#weight").val();
		var downStartDate = $("#downStartDate").val();
		var downEndDate = $("#downEndDate").val();
		var carNumber = this.carNumber;
		if (deviceId == "") {
			this.message('请选择车牌号')
			return;
		}
		var isSumit = this.isAllDateTime();

		if (!isSumit) {
			return;
		}
		let that = this;
		this.confirm_message('是否保存上卸货点').then(() => {

			$.ajax({
				type: "POST",
				url: config.BaseURL + "stats/recordtransportdata.html",
				xhrFields: {
					withCredentials: true
				},
				data: {
					"deviceId": deviceId,
					"upStartDate": upStartDate,
					"upEndDate": upEndDate,
					"weight": weight,
					"downStartDate": downStartDate,
					"downEndDate": downEndDate,
					"carNumber": carNumber
				},
				dataType: "json",
				success: function (result) {
					that.message(result.message);
				},
				error: function (errorMsg) {
					that.message('网络错误,请联系管理员');
				}
			});

		})
	}
	//定义转换时间戳函数
	changeTime(str) {
		let str1 = str.replace(/-/g, "/");
		let timestamp = new Date(str1).getTime();
		return timestamp;
	}
	mapClick: boolean = true;	//地图点击防抖节流
	//生成echart折线图
	showCheart() {
		if ($('#deviceDetailModal').attr('style').indexOf('display: block;') > 0) { //如果设备弹窗打开就刷新数据
			this.getDeviceInfoData();
			this.getTableDataTab(this.activeTab);
		}
		if (this.deviceId == '') {
			this.message('请选择需要查看的车辆');
			return;
		}
		if (this.sensorChannel) {
			this.sensorLoad();//拉取损坏传感器数据
		}
		this.startTime = $('#datetimepicker1').val();
		this.endTime = $('#datetimepicker2').val();
		$('#datetimepicker3').val(this.startTime);
		$('#datetimepicker4').val(this.endTime);
		if (this.startTime == '') {
			this.message('开始时间不能为空');
			return;
		}
		if (this.endTime == '') {
			this.message('结束时间不能为空');
			return;
		}
		let timeCheck = common.correctTimeParams(this.startTime, this.endTime, 0);
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		this.myMap.clearOverlays();
		function nullUpdate() { }
		this.carMoveCanvasLayer = new CanvasLayer({
			map: this.myMap,
			update: nullUpdate,
			zIndex: 10
		});
		this.moveCanvasLayer = new CanvasLayer({
			map: this.myMap,
			update: nullUpdate,
			zIndex: 10
		});
		this.myMap.addOverlay(this.carMoveCanvasLayer);
		this.myMap.addOverlay(this.moveCanvasLayer);
		this.askforData();
		this.clickHold(false)// 自动展开工具箱
		this.gpsRecord = []; //GPS数据更新
	}
	//创建生成异常警报弹窗
	createAbnormalInfo(infoData) {
		infoData.onTime = infoData.onTime ? infoData.onTime : '无';
		if (this.abnormalInfo) {
			this.myMap.removeOverlay(this.abnormalInfo);
		}
		let point = new BMap.Point(infoData.lng, infoData.lat);
		//			this.myMap.centerAndZoom(point, 14);
		infoData.abType = infoData.type == '1' ? '主板开关机事件' : '主机上下电事件';
		//			let colseTime=infoData.totalSecond+'秒';
		//			if(infoData.totalSecond>60){
		//				colseTime = this.convertTime(infoData.totalSecond);
		//			}
		let lostWeightHtml = '';
		if (infoData.lostime) {
			lostWeightHtml = '<li><span class="leftSpan">重量丢失：</span><span class="rightSpan"> 约' + this.convertTime(infoData.lostime) + '</span></li>';
		}
		let html = '<div class="abInfobox infoBox">' +
			'<div class="title">' + infoData.carNumber + '异常信息</div>' +
			'<div class="content">' +
			'<ul>' +
			//						'<li><span class="leftSpan">所属公司：</span><span class="rightSpan"> '+infoData.companyName+'</span></li>'+
			'<li><span class="leftSpan">异常类型：</span><span class="rightSpan"> ' + infoData.name + '</span></li>' +
			'<li><span class="leftSpan">开始时间：</span><span class="rightSpan"> ' + infoData.offTime + '</span></li>' +
			'<li><span class="leftSpan">结束时间：</span><span class="rightSpan"> ' + infoData.onTime + '</span></li>' +
			'<li><span class="leftSpan">异常时长：</span><span class="rightSpan"> ' + infoData.rangeTime + '</span></li>' +
			//						lostWeightHtml+
			'<li><span class="leftSpan">发生地址：</span><span class="rightSpan"> ' + infoData.address + '</span></li>' +
			'</ul>' +
			'</div>' +
			'<div class="abpointer"></div>' +
			'</div>';
		this.abnormalInfo = new BMapLib.InfoBox(this.myMap, html, {
			boxStyle: {
				width: "240px",
				height: "0"
			},
			offset: new BMap.Size(240, 160),
			closeIconMargin: "12px 0px 0;z-index: 1;width: 18px",
			closeIconUrl: "assets/img/trackImage/close1.png",
			enableAutoPan: true,
			align: INFOBOX_AT_TOP
		});
		let marker = new BMap.Marker(point);
		this.abnormalInfo.open(marker);
	}
	//传递子组件事件
	transferSubcomponent() {
		//传值子组件,是否获取问题记录数据 
		if (this.questionRecord) {
			this.isGetRecord = {
				status: true,
				companyId: this.selectedCompanyId,
				deviceId: this.deviceId,
				carNumber: this.carNumber,
				startDate: this.startTime,
				endDate: this.endTime,
			};
		}
		else {
			this.isGetRecord = { status: false };
		}
	}
	timeShadow: any = []; //没有历史数据区域
	//后台获取数据
	askforData() {
		this.loadometerData = [];
		this.loadometerArr = [];
		this.voltageData = [];
		let _reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime + '&showModify=' + this.showModify;
		this.jsonApiService.http2("weighbridge/weightforreal.html", _reqdata).subscribe(result => {
			if (result.data.length >= 1) {
				this.loadometerData = result.data;
			}
		})
		this.jsonApiService.http2("logForVoltage/queryLogForVoltageByParam.html", _reqdata).subscribe(result => {
			if (result.data.length >= 1) {
				this.voltageData = result.data;
			}
		})
		this.initChart();
		layer.load();
		//===============================================================计算在厂区=====================================================================================================
		this.plantArea();
		// 有公司权限,才可以预览到厂区围栏
		this.getCompanyRail();
		//		.then(()=>{
		//		    //判断车辆是否红狮车辆    返回true为红狮车辆
		//          if(this.isJudgeHS){
		//              this.getCompanyRail();
		//          }else {
		//              if(this.companyRailList.length > 0){
		//                  for(let item of this.companyRailList){
		//                      this.myMap.removeOverlay(item);
		//                  }
		//              }
		////              this.myMap.clearOverlays();
		//          }
		//		});
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime + '&showModify=' + this.showModify;
		let getDateUrl = "stats/draw.html"
		if (this.apiType == "2") {
			getDateUrl = "system/gpsweightAPI.html";
		}
		this.jsonApiService.http2(getDateUrl, reqdata).subscribe(data => {
			layer.closeAll('loading');
			this.transferSubcomponent();
			this.getVersionMessage();
			this.allData = data.data;
			if (this.allData.length < 2) {
				this.message('没有数据')
				return;
			}
			this.linetoMapData = []; //地图联动轨迹画线数据
			this.carSpeedArr = [];//画速度折线数据
			let timeValue = [];
			let len = this.allData.length;
			var lostWeight = [];//记录重量丢失的时间
			var lostWeightMark = []; //计算丢失重量的时长
			let nullGpsArr = []; //经纬度为空或者0.0的画折线数据
			var nullMarkerData = []; //计算经纬度丢失的时长
			let isLostGps = false; //是否有丢失经纬度
			var isHavePoint = 0; //控制判断经纬度丢失起始结束位置计算时间条件
			/**
			 * 计算采样周期,用于判断重量丢失的阈值
			 * 取10组历史数据,取中位数作为数据采样的频率
			 */
			let temFilterArr: any = [];
			this.filterTimeDefault = 0;
			if (len > 10) {
				for (let i = 0; i < 10; i++) {
					let time1 = this.changeTime(this.allData[i].uploadDate);
					let time2 = this.changeTime(this.allData[i + 1].uploadDate);
					let diffTime = (time2 - time1) / 1000;
					temFilterArr.push(diffTime)
				}
				temFilterArr.sort(function (a, b) {
					return a - b;
				})
				this.filterTimeDefault = Number(temFilterArr[6]) * 1.5;
			}
			//			else {
			//				this.filterTimeDefault = (this.changeTime(this.allData[1].uploadDate) - this.changeTime(this.allData[0].uploadDate)) / 1000 * 1.5;
			//			}
			if (this.filterTime) {
				this.filterTimeDefault = Number(this.filterTime) > this.filterTimeDefault ? Number(this.filterTime) : this.filterTimeDefault;
			}
			this.filterTimeDefault = this.filterTimeDefault > 150 ? this.filterTimeDefault : 150;

			/**
			 * 对筛选时间范围内,返回的历史数据做处理,对于数据缺失的时间段进行数据的补点,在echart对应显示灰色区域,表明该时间段范围内没有历史数据. 
			 */
			this.timeShadow = [];
			if (common.mmsstoTimestamp(this.allData[0].uploadDate) - common.mmsstoTimestamp(this.startTime) > this.filterTimeDefault * 1000) {
				// 判断曲线数据前有没有过磅数据,有过磅数据,显示无数据区域,没有过磅数据则不显示无数据区域
				let hasWeightInEmptyDataStartTime: boolean = false;
				for (let i = 0; i < this.loadometerData.length; i++) {
					let item = this.loadometerData[i];
					if (common.mmsstoTimestamp(this.startTime) < common.mmsstoTimestamp(item.date) && common.mmsstoTimestamp(item.date) < common.mmsstoTimestamp(this.allData[0].uploadDate)) {
						hasWeightInEmptyDataStartTime = true;
						break;
					}
				}
				if (hasWeightInEmptyDataStartTime) {
					let emptyDataStartTime = [];//存放搜索开始时间空数据补点的集合
					for (let t = common.mmsstoTimestamp(this.startTime); t < common.mmsstoTimestamp(this.allData[0].uploadDate); t = t + this.filterTimeDefault * 1000) {
						let temDate = common.getTimeMmss(new Date(t));
						let temObj = {
							aCH1: "",
							aCH2: "",
							aCH3: "",
							aCH4: "",
							aCH5: "",
							aCH6: "",
							aCH7: "",
							aCH8: "",
							aCH9: "",
							aCH10: "",
							aCH11: "",
							aCH12: "",
							aCH13: "",
							aCH14: "",
							aCH15: "",
							aCH16: "",
							checkGps: '',
							checkWeight: '',
							deviceId: this.deviceId,
							handBrakeHardwareStatus: "",
							handBrakeSoftwareStatus: "",
							mWeight: "",
							rectifyWeight: "",
							rectifyX: "",
							rectifyY: "",
							speed: "",
							uploadDate: temDate,
							weight: "",
							x: this.allData[0].x,
							y: this.allData[0].y,
						}
						emptyDataStartTime.push(temObj);
					}

					let emptyShadowStart = [{
						name: "无数据",
						xAxis: this.startTime
					}, {
						xAxis: this.allData[0].uploadDate
					}]
					this.timeShadow.push(emptyShadowStart);
					this.allData = emptyDataStartTime.concat(this.allData);
				}
			}
			if (common.mmsstoTimestamp(this.endTime) - common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) > this.filterTimeDefault * 1000) {
				// 判断曲线数据后有没有过磅数据,有过磅数据,显示无数据区域,没有过磅数据则不显示无数据区域
				let hasWeightInEmptyDataEndTime: boolean = false;
				for (let i = 0; i < this.loadometerData.length; i++) {
					let item = this.loadometerData[i];
					if (common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) < common.mmsstoTimestamp(item.date) && common.mmsstoTimestamp(item.date) < common.mmsstoTimestamp(this.endTime)) {
						hasWeightInEmptyDataEndTime = true;
						break;
					}
				}
				if (hasWeightInEmptyDataEndTime) {
					let emptyDataEndTime = [];//存放搜索结束时间空数据补点的集合
					let EndTime: string;
					if (new Date().getTime() - common.mmsstoTimestamp(this.endTime) > 0) {
						EndTime = this.endTime;
					} else {
						EndTime = common.getNowTime();
					}
					for (let t = common.mmsstoTimestamp(this.allData[this.allData.length - 1].uploadDate) + this.filterTimeDefault * 1000; t <= common.mmsstoTimestamp(EndTime); t = t + this.filterTimeDefault * 1000) {
						let temDate = common.getTimeMmss(new Date(t));
						let temObj = {
							aCH1: "",
							aCH2: "",
							aCH3: "",
							aCH4: "",
							aCH5: "",
							aCH6: "",
							aCH7: "",
							aCH8: "",
							aCH9: "",
							aCH10: "",
							aCH11: "",
							aCH12: "",
							aCH13: "",
							aCH14: "",
							aCH15: "",
							aCH16: "",
							checkGps: '',
							checkWeight: '',
							deviceId: this.deviceId,
							handBrakeHardwareStatus: "",
							handBrakeSoftwareStatus: "",
							mWeight: "",
							rectifyWeight: "",
							rectifyX: "",
							rectifyY: "",
							speed: "",
							uploadDate: temDate,
							weight: "",
							x: this.allData[this.allData.length - 1].x,
							y: this.allData[this.allData.length - 1].y,
						}
						emptyDataEndTime.push(temObj);
					}
					let emptyShadowEnd = [{
						name: "无数据",
						xAxis: this.allData[this.allData.length - 1].uploadDate
					}, {
						xAxis: emptyDataEndTime[emptyDataEndTime.length - 1].uploadDate
					}]
					this.timeShadow.push(emptyShadowEnd);
					this.allData = this.allData.concat(emptyDataEndTime);
				}
			}
			len = this.allData.length;
			for (var i = 0; i < len; i++) {
				timeValue[i] = this.allData[i].uploadDate; //x时间轴数据
				if (!this.allData[i].weight) {
					this.allData[i].weight = '-';
				}
				this.weightArr[i] = this.allData[i].weight; //重量 
				if (this.weightArr[i] < 0 && this.weightArr[i] >= -1) {
					this.weightArr[i] = 0;
				}
				let _speed = parseFloat(this.allData[i].speed); //速度
				if (_speed > -1) {
					this.carSpeedArr[i] = parseFloat(this.allData[i].speed);
				} else {
					this.carSpeedArr[i] = 0;
				}
				this.loadometerArr[i] = '-';
				nullGpsArr[i] = '-';
				//计算经纬度等于0.0或者丢失的时候是时长start
				if (!this.allData[i] || !this.allData[i].x || this.allData[i].x == '0.0') {
					if (isHavePoint < 1) {
						isHavePoint = i;
					}
				} else {
					if (isHavePoint > 0) {
						var lostTime = (this.changeTime(this.allData[i].uploadDate) - this.changeTime(this.allData[isHavePoint].uploadDate)) / 1000;
						if (lostTime > this.filterTimeDefault) {
							var point = {
								value: this.convertTime(lostTime),
								xAxis: isHavePoint,
								yAxis: this.allData[isHavePoint].weight,
								lostime: lostTime,
							};
							nullMarkerData.push(point);
						}
						isHavePoint = 0
					}
				}
				//计算end
				if (i < len - 2) {
					//获取丢失的数据
					let lostStartime = this.changeTime(this.allData[i].uploadDate);
					let lostEndtime = this.changeTime(this.allData[i + 1].uploadDate);
					let lostime = (lostEndtime - lostStartime) / 1000;
					if (lostime > this.filterTimeDefault) {//重量时间段丢失
						var point = {
							value: this.convertTime(lostime),
							xAxis: i,
							yAxis: this.allData[i].weight,
							lostime: lostime,
						};
						lostWeightMark.push(point);
					}
					if (!this.allData[i].x || this.allData[i].x == '0.0') {
						//经纬度坐标丢失
						if (i > 0) {
							isLostGps = true;
							nullGpsArr[i] = this.allData[i].weight;
						}
					}
				}
				var mapPoint = toMapPoint(this.allData[i]);
				if (mapPoint && mapPoint.lng && mapPoint.lat && mapPoint.lng !== '0.0' && mapPoint.lat !== '0.0' && mapPoint.lat != '0' && mapPoint.lng != '0') {
					this.linetoMapData[i] = this.allData[i];
				}

			}
			//查询连续性为空的经纬度数据结束空的位置
			this.passageData = [];
			//优化丢失的数据
			//			lostWeightMark=this.fillLosWeighttArr(lostWeightMark);
			//获取异常信息数据
			var self = this;
			let alertReq = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime;
			let logReq = 'deviceId=' + this.deviceId + '&startDate=' + this.startTime + '&endDate=' + this.endTime;
			this.jsonApiService.http2("alertlog/queryAllTypeDeviceShutDownAlarmList.html", alertReq).subscribe(result => {
				this.jsonApiService.http2("log/queryLogByDeviceId.html", logReq).subscribe(data => {
					let alertArr = result.data;
					let logArr = data.data;
					let temResult = [];
					if (alertArr.length > 0) {
						for (var i = 0; i < alertArr.length; i++) {
							alertArr[i].flag = 'alert';
						}
						temResult = temResult.concat(alertArr);
					}
					if (logArr.logForCoeList.length > 0) {

						for (var i = 0; i < logArr.logForCoeList.length; i++) {
							logArr.logForCoeList[i].flag = 'coef';
						}
						temResult = temResult.concat(logArr.logForCoeList);
					}
					if (logArr.UpgradeInfoList.length > 0) {
						for (var i = 0; i < logArr.UpgradeInfoList.length; i++) {
							logArr.UpgradeInfoList[i].flag = 'version';
						}
						temResult = temResult.concat(logArr.UpgradeInfoList);
					}
					//					this.powerOffAlertList = [];
					let len = temResult.length;
					let offlineError = [];
					if (len > 0) {
						for (let i = 0; i < len; i++) {
							let tim;
							let sort = 0;
							let item = temResult[i];
							let topos = toMapPoint({
								lng: item.lng,
								lat: item.lat,
							});
							if (topos) {
								item.lng = topos.lng;
								item.lat = topos.lat;
							};
							if (item.flag == 'alert') {
								tim = this.changeTime(item.offTime);
							} else if (item.flag == 'coef') {
								tim = this.changeTime(item.sendTime);
							} else if (item.flag == 'version') {
								tim = this.changeTime(item.createTime);
							}
							for (let j = sort; j < this.allData.length; j++) {
								let _item = this.allData[j];
								let _tim = this.changeTime(_item.uploadDate);
								if (_tim - tim >= 0 && j > 0) {
									sort = j;
									let errorItem: any;
									if (item.type == 1 && item.flag == 'alert') {
										errorItem = {
											name: '离线警报',
											value: '离',
											xAxis: j - 1,
											yAxis: this.allData[j - 1].weight,
											lostime: '',
											rangeTime: item.totalSecond ? this.convertTime(item.totalSecond) : '离线中',
											symbol: 'image://assets/img/trackImage/ofline_jb.png',
											symbolSize: 24,
											symbolOffset: ['0', '-50%'],
										};
									} else if (item.type == 2 && item.flag == 'alert') {
										errorItem = {
											name: '断电警报',
											value: '',
											xAxis: j - 1,
											yAxis: this.allData[j - 1].weight,
											lostime: '',
											rangeTime: item.totalSecond ? this.convertTime(item.totalSecond) : '断电中',
											symbol: 'image://assets/img/trackImage/powerOff2.png',
											symbolSize: 24,
											symbolOffset: ['0', '-50%'],
										};
										//										this.powerOffAlertList.push(item);//断电警报集合,处理echart显示断电区域使用
									} else if (item.flag == 'coef') {
										errorItem = {
											name: '系数设置',
											value: '系',
											xAxis: j - 1,
											yAxis: this.allData[j - 1].weight,
											lostime: '',
											symbol: 'image://assets/img/version_icon.png',
											symbolSize: 26,
											symbolOffset: ['0', '-50%'],
										};
									} else if (item.flag == 'version') {
										errorItem = {
											name: '固件升级',
											value: '固',
											xAxis: j - 1,
											yAxis: this.allData[j - 1].weight,
											lostime: '',
											symbol: 'image://assets/img/version_icon.png',
											symbolSize: 26,
											symbolOffset: ['0', '-50%'],
										};
									}
									if (errorItem) {
										for (let keys in item) {
											errorItem[keys] = item[keys];
										}
										offlineError.push(errorItem);
									}
									break;
								}
							}
						}
					}
					/**
					 *   处理警报不在历史数据时间范围之内,但在搜索的时间范围.  将不在历史数据时间范围的数据,补打在历史数据最后时间点上.
					 */
					for (let w = 0; w < alertArr.length; w++) {
						let itemAlert = alertArr[w];
						if (this.changeTime(itemAlert.offTime) > this.changeTime(this.allData[this.allData.length - 1].uploadDate)) {
							let errorItem: any;
							let index = alertArr.length - w;
							if (itemAlert.type == 1 && itemAlert.flag == 'alert') {
								errorItem = {
									name: '离线警报',
									value: '离',
									xAxis: this.allData.length - index,
									yAxis: this.allData[this.allData.length - index].weight,
									lostime: '',
									rangeTime: itemAlert.totalSecond ? this.convertTime(itemAlert.totalSecond) : '离线中',
									symbol: 'image://assets/img/trackImage/ofline_jb.png',
									symbolSize: 24,
									symbolOffset: ['0', '-50%'],
								};
							} else if (itemAlert.type == 2 && itemAlert.flag == 'alert') {
								errorItem = {
									name: '断电警报',
									value: '',
									xAxis: this.allData.length - index,
									yAxis: this.allData[this.allData.length - index].weight,
									lostime: '',
									rangeTime: itemAlert.totalSecond ? this.convertTime(itemAlert.totalSecond) : '断电中',
									symbol: 'image://assets/img/trackImage/powerOff2.png',
									symbolSize: 24,
									symbolOffset: ['0', '-50%'],
								};
							}
							if (errorItem) {
								for (let keys in itemAlert) {
									errorItem[keys] = itemAlert[keys];
								}
								offlineError.push(errorItem);
							}
						}
					}
					for (let i = 0; i < offlineError.length; i++) {
						let item = offlineError[i];
						let isFind = false;
						for (let _i = 0; _i < lostWeightMark.length; _i++) {
							let iem = lostWeightMark[_i];
							if (iem.flag) {
								if (item.xAxis == iem.xAxis) {
									item.xAxis = item.xAxis + 1;
									item.lostime = iem.lostime;
									lostWeightMark.push(item);
									isFind = true;
									break;
								}
							} else {
								if ((item.xAxis < iem.xAxis + 1 && item.xAxis > iem.xAxis - 1) || (item.xAxis == iem.xAxis)) {
									item.lostime = iem.lostime;
									lostWeightMark[_i] = item;
									isFind = true;
									break;
								}
							}
						}
						if (!isFind) lostWeightMark.push(item);
					}
					this.passageData.push({
						name: '重量（吨）',
						type: 'line',
						borderWidth: 5,
						itemStyle: {
							color: '#c23531',
						},
						data: this.weightArr,
						markArea: {
							itemStyle: {
								color: '#ddd',
								opacity: 0.5,
							},
							label: {
								color: '#333',
								fontSize: "16",
								position: ['50%', '50%'],
								offset: [-24, -8]
							},
							emphasis: {
								itemStyle: {
									color: '#ddd',
									opacity: 0.5,
								},
								label: {
									position: ['50%', '50%'],
									offset: [-24, -8]
								}
							},
							data: this.timeShadow,
						},
						markPoint: {
							data: lostWeightMark,
							itemStyle: {
								normal: {
									label: {
										fontSize: 10
									}
								}
							}
						}
					})

					if (isLostGps) {
						this.passageData.push({
							name: '',
							type: 'line',
							itemStyle: {
								color: 'gray'
							},
							lineStyle: {
								width: 3, //折线宽度
							},
							data: nullGpsArr,
							markPoint: {
								data: nullMarkerData
							}
						})
					}
					//时间轴
					this.echartOption.xAxis.data = timeValue;
					//ad信号
					this.showAdSignal();
					if (this.carSpeed) {
						this.yAxiSpeed.min = 0;
						this.yAxiSpeed.max = 120;
						this.showCarSpeed();
					}
					if (this.loadometer) {
						this.showLoadometer();
						//=============================================================红狮车辆:在厂区打点========================================================================
						this.countPont('2'); //显示在厂区
					}

					this.yAxiSignal.show = this.lookSignal;
					this.yAxiSpeed.show = this.carSpeed;
					this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed];
					this.echartOption.series = this.passageData;
					this.legendSleced['手刹信号'] = false;
					this.echartOption.legend.selected = this.legendSleced;
					//this.myChart.setOption(this.echartOption, true);
					//this.showMapTrack();
					this.jsonApiService.http2("realtime/getRealTimeDataForBase.html", 'deviceId=' + this.deviceId).subscribe(result => {
						if (result.data.unit == '2') {
							this.echartOption.series[0].name = '重量（千克）';
						}
						this.myChart.setOption(this.echartOption, true);
						this.showMapTrack();
						this.voltageChange();
					})
				})
			})
		})
	}
	//计算两个坐标点的距离
	GetDistance(lat1, lng1, lat2, lng2) {
		var radLat1 = lat1 * Math.PI / 180.0;
		var radLat2 = lat2 * Math.PI / 180.0;
		var a = radLat1 - radLat2;
		var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378.137;// EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}
	//厂区在线的经纬度点
	isJudgeHS: any = false //判断是不是红狮
	//计算是否厂区在线
	plantArea() {
		var that = this;
		return new Promise(function (resolve, error) {
			that.jsonApiService.http2("realtime/getRealTimeDataForBase.html", 'deviceId=' + that.deviceId).subscribe(result => {
				//判断是不是红狮
				that.jsonApiService.http("company/isHongShiCar.html", 'companyId=' + result.data.companyId).subscribe(result2 => {
					if (result2.success) {
						//判断是不是红狮
						if (result2.data == 1) {
							that.isJudgeHS = true;
						} else {
							that.isJudgeHS = false;
						}
					}
					resolve();
				})

			})
		})
	}
	// 处理红狮车辆  ,计算该车进入厂区的位置,标记在曲线图上
	countPont(type) {
		//isJudgeHS:true  查看车属于红狮的标识
		if (!this.isJudgeHS) return
		var that = this;
		var len = that.allData && that.allData.length;
		var pointWeightMark = []; //厂区内的点
		var isweightCount = false;
		var pointObj;

		for (var k = 0; k < that.passageData.length; k++) {
			if (that.passageData[k].name == '在厂区内') {
				that.passageData.splice(k, 1);
			}
		}
		// 绘制红狮围栏 [以公司经纬度为圆心,半径1000米],计算车辆轨迹是否经过围栏
		//      console.log(this.companyRailList,'============companyRailList=======')
		if (this.companyRailList.length > 0 && this.companyRailList.length > 0 && this.isJudgeHS) {
			let drivePathFirstPoint = { lng: this.allData[0].lng, lat: this.allData[0].lat };
			this.inTimeArr = [];
			this.outTimeArr = [];
			for (var r = 0; r < this.companyRailList.length; r++) {
				let distance = common.caculationDistance(drivePathFirstPoint, this.companyRailList[r].point)
				// 曲线点距离公司距离1000公里以上剔除,不用考虑监控是否进入围栏
				if (distance < 1000000) {
					this.getInOutTimeArr(0, this.companyRailList[r], this.companyDataList[r]);
				}
			}
			//          console.log(this.inTimeArr,'============inTimeArr==11=====')
			//          console.log(this.outTimeArr,'============outTimeArr==11=====')
			// 对于进去围栏时间区间小于10分钟的情况剔除,不考虑是进入厂区,认为是路过[途径]围栏区域
			for (var i = 0; i < this.inTimeArr.length; i++) {
				let diffTime = common.mmsstoTimestamp(this.outTimeArr[i].endTime) - common.mmsstoTimestamp(this.inTimeArr[i].startTime)
				if (diffTime < 10 * 60 * 1000) {
					this.inTimeArr.splice(i, 1);
					this.outTimeArr.splice(i, 1);
					i = i - 1;
				}
			}
			//          console.log(this.inTimeArr,'============inTimeArr===22====')
			//          console.log(this.outTimeArr,'============outTimeArr===22====')
		}
		//是否勾选地磅数据并且地磅是否有数据
		if (that.loadometer && that.loadometerData && that.loadometerData.length == 0) {
			if (len > 2) {
				var dataArray = [];
				for (var i = 0; i < len; i++) {
					if (i < len - 2) {
						for (var w = 0; w < this.inTimeArr.length; w++) {
							// 只对进入围栏区域的点进行处理计算
							if (this.inTimeArr[w].index < i && i < this.outTimeArr[w].index) {
								let lostStartime1 = that.changeTime(that.allData[i].uploadDate);
								let lostEndtime1 = that.changeTime(that.allData[i + 1].uploadDate);
								var _weight = parseFloat(that.allData[i + 1].weight);
								//判断上货地点 且有重量存在
								if (that.allData[i].weight == "0.0" && parseFloat(that.allData[i].weight) < _weight && lostStartime1 < lostEndtime1) {
									let n = 15;
									if (i + n < len - 13) {
										let lostStartime = that.changeTime(that.allData[n].uploadDate);
										let lostEndtime = that.changeTime(that.allData[n + 1].uploadDate);
										if (lostStartime < lostEndtime) {
											while (n < len - i - 13) {
												n = n + 1;
												let pointweight = parseFloat(that.allData[i + n].weight);
												let _weight1 = parseFloat(that.allData[i + n + 2].weight);
												let _weight2 = parseFloat(that.allData[i + n + 4].weight);
												let _weight3 = parseFloat(that.allData[i + n + 8].weight);
												let _weight4 = parseFloat(that.allData[i + n + 12].weight);
												let jssuanweight = (_weight1 + _weight2 + _weight3 + _weight4) / 4
												if (Math.abs(jssuanweight - pointweight) < 1 && parseFloat(that.allData[i + n].speed) > 1) {
													break;
												}

											}
										}
									}
									var startWeight = that.allData[i].weight;
									var startUploadDate = that.allData[i].uploadDate;
									var startLeaveTime = that.allData[i + n].uploadDate;
									pointObj = {
										name: '在厂区内',
										value: "",
										xAxis: i - 1,
										yAxis: startWeight,
										lostime: this.inTimeArr[w].startTime,
										companyName: this.inTimeArr[w].companyName,
										symbol: 'image://assets/img/trackImage/company.png',
										symbolSize: [34, 44],
										symbolOffset: ['0', '-50%'],
										carNumber: that.carNumber,
										leaveTime: this.outTimeArr[w].endTime,
									};
									pointWeightMark.push(pointObj);
								}
							}
						}
					}
				}
				//计算没有上货点的情况下,进入厂区围栏的情况
				let otherPoint: any = [], aver: number, isFind: boolean = false;
				for (var w = 0; w < this.inTimeArr.length; w++) {
					isFind = false;
					for (let j = 0; j < pointWeightMark.length; j++) {
						if (this.inTimeArr[w].index < pointWeightMark[j].xAxis && pointWeightMark[j].xAxis < this.outTimeArr[w].index) {
							isFind = true;
							continue;
						}
					}
					if (!isFind) {
						aver = Math.floor((this.inTimeArr[w].index + this.outTimeArr[w].index) / 2);//取进入围栏和出围栏中间点作为在厂区标识
						if (!otherPoint.includes(aver)) {
							let pointObj = {
								name: '在厂区内',
								value: "",
								xAxis: aver - 1,
								yAxis: '0.0',
								companyName: this.inTimeArr[w].companyName,
								lostime: this.inTimeArr[w].startTime,
								symbol: 'image://assets/img/trackImage/company.png',
								symbolSize: [34, 44],
								symbolOffset: ['0', '-50%'],
								carNumber: that.carNumber,
								leaveTime: this.outTimeArr[w].endTime,
							};
							otherPoint.push(aver);
							pointWeightMark.push(pointObj);
						}
					}
				}
				//				console.log(otherPoint)
				//				console.log(pointWeightMark,'=======666666666666========')
				this.passageData.push({
					name: '在厂区内',
					type: 'line',
					borderWidth: 0,
					itemStyle: {
						color: '#37a2da',
					},
					lineStyle: {
						width: 1,
					},
					markPoint: {
						data: pointWeightMark
					}
				})
				this.echartOption.series = this.passageData;
				//              console.log(this.passageData,'this.passageData===================')
			}
		} else {
			let lens = that.passageData.length;
			for (var i = 0; i < lens; i++) {
				if (that.passageData[i].name === '在厂区内') {
					that.passageData.splice(i, 1);
					break;
				}
			}
			that.echartOption.series = that.passageData;
			if (type == '1') { that.myChart.setOption(that.echartOption, true) };
		}

	}
	// 获取公司经纬度,绘制围栏,如果是红狮车辆,则计算是否进入围栏[厂区]
	companyRailList: any = [];//公司围栏
	companyDataList: any = [];//公司数据
	getCompanyRail() {
		let railStyle = {
			strokeColor: 'blue',
			fillColor: 'red',
			strokeWeight: 1,
			strokeOpacity: 0.2,
			fillOpacity: 0.2
		};
		this.jsonApiService.http_obj("company/queryLowestLevelCompany.html", { deviceId: this.deviceId }).subscribe(result => {
			if (result.data && result.data.length > 0) {
				//	            this.myMap.clearOverlays();
				if (this.companyRailList.length > 0) {
					for (let item of this.companyRailList) {
						this.myMap.removeOverlay(item);
					}
				}
				this.companyRailList = [];
				this.companyDataList = [];
				let companyList = result.data;
				for (let item of companyList) {
					let mapPoint = toMapPoint({ lng: item.lng, lat: item.lat });
					if (item.lng && item.lat) {
						this.companyDataList.push(item);
						let point = new BMap.Point(mapPoint.lng, mapPoint.lat);//红狮公司经纬度数据坐标为百度坐标系
						let circle = new BMap.Circle(point, 1000, railStyle); //创建圆
						this.companyRailList.push(circle);
						this.myMap.addOverlay(circle);
					}
				}
			}
		})
	}
	//getInOutTimeArr：计算进入跟离开行政区的时间点
	inTimeArr: any = [];//记录进入围栏的时间
	outTimeArr: any = [];//记录离开围栏的时间
	inCompantList: any = [];//记录进入厂区,离开厂区的数据
	getInOutTimeArr(order, chartAreaPly, companyData) {
		let trackData = this.allData;
		var isOut = false; //判断是否再进入边界后又再次出去
		var len = trackData.length;
		for (var i = order; i < len; i++) {
			if (trackData[i].lng && trackData[i].lat) {
				var comparePoint = new BMap.Point(trackData[i].lng, trackData[i].lat);
				var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, chartAreaPly);
				if (result) { //在内部，把该点显示在地图上  
					this.inTimeArr.push({ startTime: trackData[i].uploadDate, index: i, companyName: companyData.companyName });
					for (var j = i; j < len; j++) {
						var comparePoint = new BMap.Point(trackData[j].lng, trackData[j].lat);
						var result = BMapLib.GeoUtils.isPointInPolygon(comparePoint, chartAreaPly);
						if (!result) { //在内部，把该点显示在地图上  
							isOut = true; //判断是否再进入边界后又再次出去
							this.outTimeArr.push({ endTime: trackData[j].uploadDate, index: j, companyName: companyData.companyName });
							if (j < len) {
								this.getInOutTimeArr(j, chartAreaPly, companyData);
							}
							break;
						}
					}
					if (!isOut) {
						this.outTimeArr.push({ endTime: trackData[len - 1].uploadDate, index: len - 1, companyName: companyData.companyName });
					}
					break;
				}
			}
		}
	}





	fillLosWeighttArr(paramArr) {
		let result = [];
		let len = paramArr.length;
		if (len > 30) {
			let eq = Math.floor(this.allData.length / 100);
			let multiple = 1.5;//倍数
			for (let i = 0; i < len - 1; i++) {
				let item1 = paramArr[i];
				let item2 = paramArr[i + 1];
				if (i < 1) {
					result.push(item1);
				} else {
					let sort = item2.xAxis - item1.xAxis;
					if (sort > eq || item2.lostime > item1.lostime * multiple || item2.lostime < item1.lostime / multiple) {
						result.push(item1);
					}
				}
			}
			if (len > 1) {
				let lastItem = paramArr[len - 1];
				result.push(lastItem);
			}
		}
		else {
			result = paramArr;
		}
		return result;
	}

	//绘画车辆速度折线
	showCarSpeed() {
		let obj = {
			name: '车辆速度',
			type: 'line',
			yAxisIndex: 2,
			itemStyle: {
				normal: {
					color: '#5793f3',
					lineStyle: {
						width: 1, //折线宽度
						opacity: 0.5,
					}
				}
			},
			data: this.carSpeedArr,
			areaStyle: {
				color: 'rgba(83, 146, 230,0.5)'
			}
		};
		this.passageData.push(obj);
	}
	//绘画ad信号折线,及丢失数据点.
	showAdSignal() {
		this.passageName = [];
		this.passageArr = [];
		var data = this.allData;
		var len = data.length;
		let wareStatusArr = [];//手刹信号
		//nullPassArr中对应的值为空的时候,从allPassArr移除对应的通道数据,最终得到filterArr过滤后的数据this.passageArr
		var allPassArr = [];//16通道所有的数组        
		var nullPassArr = [];//记录通道全部数据是否为空.,默认值为true
		for (var z = 0; z < 16; z++) {
			var newArr = new Array();
			allPassArr.push(newArr);
			nullPassArr.push(true);
		}
		for (var i = 0; i < len; i++) {
			var handSingal = parseFloat(data[i].handBrakeHardwareStatus) * 10 * this.multiple;//手刹信号放大10万倍
			if (handSingal >= 0 || handSingal < 0) {
				wareStatusArr[i] = handSingal;
			}
			for (var j = 0; j < 16; j++) {
				var name = 'aCH' + (j + 1);
				var passVal = parseFloat(data[i][name]);//获取16个通道的值;
				allPassArr[j][i] = passVal;
				if (passVal > 0 || passVal < 0) {
					nullPassArr[j] = false;
				}
			}
		}

		this.legendSleced = {};
		for (var _z = 0; _z < nullPassArr.length; _z++) {
			if (!nullPassArr[_z]) {
				var passName = '通道' + (_z + 1);
				this.passageName.push(passName);
				this.passageArr.push(allPassArr[_z]);

				if (this.hideOrshowline.indexOf(passName) > -1) {
					this.legendSleced[passName] = true;
				} else {
					this.legendSleced[passName] = false;
				}

			}
		}
		if (!nullPassArr[15]) {
			// 当16通道的值不为空时候
			this.signal16Arr = allPassArr[15];
			this.isRate16 = true;
		}
		else {
			this.isRate16 = false;
		}
		if (wareStatusArr.length > 1) {
			this.passageName.push('手刹信号');
			this.passageArr.push(wareStatusArr);
		}

		if (this.lookSignal) {

			for (var _i = 0; _i < this.passageName.length; _i++) {
				var obj = {
					name: this.passageName[_i],
					type: 'line',
					yAxisIndex: 1,
					itemStyle: {
						color: common.lineGetColor(_i)
					},
					lineStyle: {
						width: 2, //折线宽度
						opacity: 0.75
					},
					data: this.passageArr[_i]
				};
				if (this.passageName[_i] === '手刹信号') {
					obj.itemStyle = {
						color: '#8B668B'
					};
					obj.yAxisIndex = 0;
				}
				this.passageData.push(obj);
			}
		}
	}
	//地图联动绘画轨迹路线.
	showMapTrack() {
		let pointArr = this.linetoMapData;
		let map = this.myMap;
		//绘制路线

		var geturl = config.BaseURL;
		let lineStyle = { star: true, end: false, color: true, infoUrl: geturl };
		drawTrackLine(pointArr, map, lineStyle);
		setTimeout(function () {
			map.centerAndZoom(new BMap.Point(pointArr[pointArr.length - 1].lng, pointArr[pointArr.length - 1].lat), 12);
		}, 10);
		let that = this;
		let promptBox = $('.weightPromptBox');
		let alertPromptBox = $('.alertPromptBox');
		let versionChartModuleBox = $('.versionChartModuleBox');
		let coefChartModuleBox = $('.coefChartModuleBox');
		let companyChartModuleBox = $('.companyChartModuleBox');
		this.myChart.on('mouseout', function (params) {
			promptBox.hide();
			alertPromptBox.hide();
			versionChartModuleBox.hide();
			coefChartModuleBox.hide();
			companyChartModuleBox.hide();
		})
		var options = {
			size: 7,
			shape: 3,
			color: 'rgba(0, 0, 0, 0)'
		};
		this.myChart.on('mousemove', function (params, event) {
			if (that.isMoveFlag) {
				that.isMoveFlag = false;
				if (params.seriesType === 'scatter') {
					// 点击地磅数据的点
					var e = event || window.event;
					var x1 = $('#content').offset().left;
					var y1 = $('#content').offset().top;
					var x = e.clientX - x1 - 20 - promptBox.width();
					var y = e.clientY - y1 - 20 - promptBox.height();
					that.poundWeight = params.data;//当前地磅重量
					that.errorValue = common.twoDecimal(that.allData[params.dataIndex].weight * that.multiple - params.data);//重量误差值
					if (params.data == 0) {
						that.errorRate = '';
					}
					else {
						that.errorRate = common.twoDecimal(Math.abs(that.errorValue / params.data) * 100);//重量误差率 
					}
					if (that.isRate16) {
						that.ad16Value = common.twoDecimal(that.signal16Arr[params.dataIndex] * that.multiple - params.data);//16通道信号误差值
						if (that.ad16Value == 0) {
							that.ad16Rate = 0;
						}
						else {
							if (params.data == 0) {
								that.ad16Rate = '';
							}
							else {
								that.ad16Rate = common.twoDecimal(Math.abs(that.ad16Value / params.data) * 100);//16通道信号误差率
							}
						}
					}
					promptBox.show().animate({ left: x + 'px', top: y + 'px' }, 10);
				}
				else {
					promptBox.hide();
				}
				if (params.componentType === 'markPoint') {
					if (params.name == "离线警报" || params.name == "断电警报") {
						params.data.onTime = params.data.onTime ? params.data.onTime : '无';
						that.alertChartModelInfo = params.data;
						var e = event || window.event;
						var x = e.offsetX - 272;
						var y = (e.offsetY - 32) > 260 ? e.offsetY - 32 : e.offsetY - 120;
						alertPromptBox.show().animate({ left: x + 'px', top: y + 'px' }, 10);
					}
					if (params.name == "固件升级") {
						that.versionChartModuleInfo = params.data;
						var e = event || window.event;
						var x = e.offsetX - 384;
						var y = (e.offsetY - 32) > 260 ? e.offsetY - 32 : e.offsetY - 80;
						versionChartModuleBox.show().animate({ left: x + 'px', top: y + 'px' }, 10);
					}

					if (params.name == "系数设置") {
						that.coefChartModuleInfo = params.data;
						var e = event || window.event;
						var x = e.offsetX - 324;
						var y = (e.offsetY - 32) > 260 ? e.offsetY - 32 : e.offsetY - 80;
						coefChartModuleBox.show().animate({ left: x + 'px', top: y + 'px' }, 10);
					}

					if (params.name == "在厂区内") {
						that.companyChartModuleInfo = params.data;
						var e = event || window.event;
						var x = e.offsetX - 250;
						var y = e.offsetY - 10;
						companyChartModuleBox.show().animate({ left: x + 'px', top: y + 'px' }, 10);
					}
				}
				that.myMap.closeInfoWindow(); //关闭信息窗口
				setTimeout(() => {
					that.isMoveFlag = true;
				}, 80);
			}
		})
	}
	//折线移动,地图轨迹添加坐标位置点函数
	lineMoveCarPoint(data) {
		console.log('============line   move===========')
		if (data.lat > 0) {
			var mp = this.myMap;
			var update = function update() {
				var ctx = this.canvas.getContext("2d");
				if (!ctx) {
					return;
				}
				ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
				var point = new BMap.Point(data.lng, data.lat);
				var pixel = mp.pointToPixel(point);
				ctx.beginPath();
				ctx.strokeStyle = '#d0d4d7';
				ctx.arc(pixel.x, pixel.y, 35, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = 'rgba(35, 152, 255, 0.14)';
				ctx.arc(pixel.x, pixel.y, 34, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.strokeStyle = '#c2c2c4';
				ctx.arc(pixel.x, pixel.y, 8, 0, 2 * Math.PI);
				ctx.stroke();
				ctx.beginPath();
				ctx.fillStyle = '#fff';
				ctx.arc(pixel.x, pixel.y, 7, 0, 2 * Math.PI);
				ctx.fill();
				ctx.beginPath();
				ctx.fillStyle = '#1496ff';
				ctx.arc(pixel.x, pixel.y, 2.6, 0, 2 * Math.PI);
				ctx.fill();
			};
			if (typeof this.carMoveCanvasLayer != 'undefined') {
				this.carMoveCanvasLayer.options.update = update;
				this.carMoveCanvasLayer._draw();
				return;
			}
			this.carMoveCanvasLayer = new CanvasLayer({
				map: this.myMap,
				update: update,
				zIndex: 10
			});

		}
	}
	//地磅数据赋值到对应的折线数据位置上,若数据上有值则往后移
	loadometerVoluation(sort, weight) {
		if (sort + 1 <= this.loadometerArr.length) {
			if (this.loadometerArr[sort + 1] == '-') {
				this.loadometerArr[sort + 1] = weight;
			}
			else {
				this.loadometerVoluation(sort + 1, weight);
			}
		}
	}
	//获取地磅数据在chart图表显示.
	showLoadometer() {
		var orderIndex = 0;
		for (var x = 0; x < this.loadometerData.length; x++) {
			var time1 = common.mmsstoTimestamp(this.loadometerData[x].date);
			for (var i = orderIndex; i < this.allData.length; i++) {
				var time2 = common.mmsstoTimestamp(this.allData[i].uploadDate);
				orderIndex++;
				if (time2 - time1 >= 0) {
					let lmWeight = parseFloat(this.loadometerData[x].weight);
					this.loadometerVoluation(i - 1, lmWeight);
					break;
				}
			}
		}
		if (this.loadometerData.length >= 1) {
			let obj = {
				name: '地磅数据',
				type: 'scatter',
				yAxisIndex: 0,
				itemStyle: {
					color: 'orange'
				},
				data: this.loadometerArr
			};
			this.passageData.push(obj);
		}
	}

	//ad信号选中画信号折线
	signalChange() {
		let len = this.passageArr.length;
		if (len >= 1) {
			if (this.lookSignal) {

				for (var i = 0; i < len; i++) {
					//添加传感器通道数据
					var obj = {
						name: this.passageName[i],
						type: 'line',
						yAxisIndex: 1,
						itemStyle: {
							color: common.lineGetColor(i)
						},
						lineStyle: {
							width: 2, //折线宽度
							opacity: 0.75
						},
						data: this.passageArr[i]
					};
					if (this.passageName[i] === '手刹信号') {
						obj.itemStyle = {
							color: '#8B668B'
						};
						obj.yAxisIndex = 0;
					}
					this.passageData.push(obj);
				}
			} else {
				var _len = this.passageData.length;

				for (var _i = 0; _i < _len; _i++) {

					let findIndex = this.passageName.indexOf(this.passageData[_i].name);
					if (findIndex > -1) {
						this.passageData.splice(_i, 1);
						_len = _len - 1;
						_i = _i - 1;
					}

				}
			}
			this.yAxiSignal.show = this.lookSignal;
			this.yAxiSpeed.show = this.carSpeed;
			this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed];
			this.echartOption.series = this.passageData;
			this.myChart.setOption(this.echartOption, true);
		}
	}
	//地磅数据选中画折线
	loadometerChange() {
		if (!this.carNumber) {	//无车牌号则清空设备id
			this.deviceId = '';
		}
		//拉取磅单数量
		if (this.selectedCompanyId) {
			this.queryCarListByCompanyId();
		}
		if (this.allData.length < 2) {
			return;
		}

		if (this.loadometerData.length >= 1) {

			if (this.loadometer) {
				this.showLoadometer();
			} else {
				let len = this.passageData.length;
				for (var i = 0; i < len; i++) {
					if (this.passageData[i].name === '地磅数据') {
						this.passageData.splice(i, 1);
						break;
					}
				}
			}
			this.echartOption.series = this.passageData;
			this.myChart.setOption(this.echartOption, true);
		} else {
			this.countPont('1');
			this.myChart.setOption(this.echartOption, true);
			if (this.loadometer) {
				this.message('该时间段没有地磅数据');

			}
		}
	}
	//车辆速度选中画折线
	carSpeedChange() {
		if (this.carSpeedArr.length >= 1) {
			if (this.carSpeed) {
				this.yAxiSpeed.min = 0;
				this.yAxiSpeed.max = 120;
				this.showCarSpeed();
			} else {
				this.yAxiSpeed.min = undefined;
				this.yAxiSpeed.max = undefined;
				let len = this.passageData.length;
				for (var i = 0; i < len; i++) {
					if (this.passageData[i].name === '车辆速度') {
						this.passageData.splice(i, 1);
						break;
					}
				}
			}
			this.yAxiSignal.show = this.lookSignal;
			this.yAxiSpeed.show = this.carSpeed;
			this.echartOption.yAxis = [this.yAxiWeight, this.yAxiSignal, this.yAxiSpeed];
			this.echartOption.series = this.passageData;
			this.myChart.setOption(this.echartOption, true);
		}
	}
	//修正数据选中画折线
	modifyChange() {
		if (this.allData.length < 1) {
			return;
		}
		this.askforData();
	}


	//选中需要输入框获取折线图上的时间,添加endueTime类事件
	inpSelectEvent(val) {
		this.inpSelect = val;
	}

	//转换时间格式
	convertTime(timeInt) {
		var d, h, m, s;
		if (timeInt >= 0) {
			d = Math.floor(timeInt / 60 / 60 / 24);
			h = Math.floor(timeInt / 60 / 60 % 24);
			m = Math.floor(timeInt / 60 % 60);
			s = Math.floor(timeInt % 60);
		}
		if (d < 1) {
			if (h < 1) {
				// 	 return m+'分'+s+'秒';
				return '约' + m + '分';
			} else {
				return h + '小时' + m + '分';
			}
		} else {
			return d + '天' + h + '小时' + m + '分';
		}
	}
	openConfigView(modal) {
		if (!this.deviceId) {
			this.jsonApiService.message('未选择车辆');
			return
		};
		modal.show();
		this.coefCarNumber = $('#select2-carNumberSelect2-container').attr('title');
		this.getConfigParams();
	}
	closeConfigView(modal) {
		modal.hide();
	}

	initCoefficientList() {
		this.coefficientList = [];
		for (let i = 0; i < 16; i++) {
			let obj = {
				coef: '',
				index: (i + 1),
			}
			this.coefficientList.push(obj);
		}
	}

	getConfigParams() {
		let reqdata = 'deviceId=' + this.deviceId;
		this.jsonApiService.http("realtime/getRealTimeData.html", reqdata).subscribe(result => {
			if (!result.data.coef) return;
			if (result.data.runStatus !== '0') this.coefCarStatus = 'online';
			for (let i = 0; i < result.data.coef.length; i++) {
				this.coefficientList[i].coef = result.data.coef[i];
			}
		})
	}
	submitConfigMapped(modal) {
		modal.show();
		let params = {
			protocolVersion: "2",
			online: this.coefCarStatus,
			deviceId: this.deviceId,
		}
		for (let item of this.coefficientList) {
			let keys = 'channel' + item.index;
			params[keys] = item.coef;
		}
		let reqdata = '';
		for (let keys in params) {
			reqdata = reqdata + keys + '=' + params[keys] + '&';
		}
		reqdata = reqdata.substring(0, reqdata.length - 1);
		this.jsonApiService.http2("system/remotetuning.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
		})


	}
	startTime_problem: string = '';
	endTime_problem: string = '';
	isPush = '0';
	initProTypeOptions() {
		this.proTypeOptions = problemOptions.initProTypeOptions;

	}
	//监听问题类型改变事件
	problemTypeChange() {
		if (this.proTypeParams.problemType == '') return;
		let sort = +this.proTypeParams.problemType;
		this.proSlectedItem = this.proTypeOptions[sort];
		this.proTypeParams.problemClass = '';
		this.problemClassChange();
	}
	//监听问题分类改变事件
	pcIsOther = false;
	otherInpMess = '';
	problemClassChange() {
		this.seneorPhenlist = [];
		this.proTypeParams.phenomenon = '';
		this.otherInpMess = '';
		this.isPush = '0';
		//		判断选的是不是其他
		let isOther = this.proSlectedItem.childs[+this.proTypeParams.problemClass].name;
		if (isOther == '其他') {
			this.pcIsOther = true;
		} else {
			this.pcIsOther = false;
		}
		if (this.proTypeParams.problemType == "1" && this.proTypeParams.problemClass == "1") {

		}
		else {
			this.problemPhenChange();
		}
	}
	//监听问题现象改变事件
	problemPhenChange() {
		this.proTypeParams.repairGuide = '';
		this.proTypeParams.repairWay = '';
		this.proTypeParams.pheDescribe = '';
	}
	addseneorPhenItem() {
		let sensor = $('#sensorPhenName').val();
		if (!sensor || !this.proTypeParams.phenomenon) {
			this.jsonApiService.message('请选择传感器问题现象');
			return;
		}
		let len = this.seneorPhenlist.length;
		let itemId = 1;
		if (len > 0) {
			itemId = this.seneorPhenlist[len - 1].index + 1;
		}

		let phen = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name;
		let isAdd = true;
		for (let item of this.seneorPhenlist) {
			if (item.phenomenon == phen) {
				let str = '传感器' + sensor;
				if (str == item.sensorName) {
					isAdd = false;
					break;
				}
			}
		}
		if (isAdd) {
			let pheItem = {
				index: itemId,
				sensorName: '传感器' + sensor,
				phenomenon: phen,
			}
			this.seneorPhenlist.push(pheItem);
		} else {
			this.jsonApiService.message('现象已存在,不需要重复添加');
		}


	}
	delSeneorPhenItem(index) {
		this.jsonApiService.confirm_message("确定删除该条现象?").then(() => {
			this.seneorPhenlist.splice(index, 1);
		})
	}

	getSelectedVAL() {
		var result: any = {
			problemTypeStr: this.proSlectedItem.name, //问题类型
			problemClassStr: '',
			phenomenonStr: '',
			repairGuideStr: '',
			repairWayStr: '',
			pheDescribeStr: '',
			resultPhenStr: '',
		}
		if (!this.proSlectedItem) {
			this.jsonApiService.message('请选择问题类型');
			return result;
		};
		if (this.proTypeParams.problemClass) {
			//问题分类
			result.problemClassStr = this.proSlectedItem.childs[+this.proTypeParams.problemClass].name;
		}
		if (this.proTypeParams.phenomenon) {
			//问题现象
			result.phenomenonStr = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name;
			result.resultPhenStr = result.phenomenonStr;
		}
		if (this.proTypeParams.repairGuide) {
			//维修指导
			result.repairGuideStr = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].repairGuide[+this.proTypeParams.repairGuide].name;
		}
		if (this.proTypeParams.repairWay) {
			//维修方式
			result.repairWayStr = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].repairWay[+this.proTypeParams.repairWay].name;
		}
		if (this.proTypeParams.pheDescribe) {
			//维修描述
			result.pheDescribeStr = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].pheDescribe[+this.proTypeParams.pheDescribe].name;
		}

		if (this.seneorPhenlist.length > 0) {
			let list = [];
			for (let item of this.seneorPhenlist) {
				let str = item.sensorName + '-' + item.phenomenon;
				list.push(str)
			}
			result.resultPhenStr = list.join(',');

		}
		if (this.pcIsOther) {
			result.resultPhenStr = this.otherInpMess;
		}
		return result;

	}

	submitRecord() {
		if (!this.deviceId) {
			this.jsonApiService.message('先选择车辆...');
			return;
		}
		if (!this.proTypeParams.problemType) {
			this.jsonApiService.message('请选择问题分类');
			return;
		}
		if (!this.startTime_problem || !this.endTime_problem) {
			this.jsonApiService.message('问题起始时间不能为空...');
			return;
		}
		let timeCheck = common.correctTimeParams(this.startTime_problem, this.endTime_problem, 0);
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let operaParam = this.getSelectedVAL();
		if (this.proTypeParams.problemType == '1' && this.proTypeParams.problemClass == '1') {
			let sensor = $('#sensorPhenName').val();
			if (this.seneorPhenlist.length < 1 && !sensor && !this.proTypeParams.phenomenon) {
				this.jsonApiService.message('请确认添加传感器问题现象');
				return;
			}
			if (sensor && this.proTypeParams.phenomenon) {
				let phen = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name;
				let phenResult = '传感器' + sensor + '-' + phen;
				if (this.seneorPhenlist.length < 1) {
					operaParam.resultPhenStr = phenResult;
				}
				else {
					let findIndex = operaParam.resultPhenStr.indexOf(phenResult)
					if (findIndex < 0) {
						operaParam.resultPhenStr = operaParam.resultPhenStr + ',' + phenResult;
					}
				}

			}
		}
		if (!this.proTypeParams.problemType || !this.proTypeParams.problemClass) {
			this.jsonApiService.message('请选择问题分类');
			return;
		}
		if (operaParam.resultPhenStr == '') {
			this.jsonApiService.message('问题现象不能为空');
			return;
		}
		let proType = (+this.proTypeParams.problemType + 1) + '0' + (+this.proTypeParams.problemClass + 1);
		if (operaParam.problemClassStr == '其他') {
			proType = (+this.proTypeParams.problemType + 1) + '00';
		}
		this.jsonApiService.http("realtime/getRealTimeData.html", 'deviceId=' + this.deviceId).subscribe(result => {
			let params = {
				programType: proType,
				deviceId: this.deviceId,
				version: result.data.version ? result.data.version : '',
				startDate: this.startTime_problem,
				endDate: this.endTime_problem,
				reason: operaParam.resultPhenStr,
				exceptionType: +this.proTypeParams.problemType + 1,
				repairedGuide: operaParam.repairGuideStr,
				isPush: this.isPush,
				coefficient: result.data.coef ? result.data.coef : ''
			}
			let reqdata = '';
			for (let keys in params) {
				reqdata = reqdata + keys + '=' + params[keys] + '&';
			}
			reqdata = reqdata.substring(0, reqdata.length - 1);
			this.jsonApiService.http("dataExceptionRecord/addDataException.html", reqdata).subscribe(result2 => {
				this.jsonApiService.message(result2.message);
				if (result2.success) {
					this.isDisable = false;
					//					this.load();
				}
			})
		})
	}


	//提交到设备故障记录
	submitDevice() {
		if (!this.deviceId) {
			this.jsonApiService.message('先选择车辆...');
			return;
		}
		if (!this.startTime_problem || !this.endTime_problem) {
			this.jsonApiService.message('问题起始时间不能为空...');
			return;
		}
		let timeCheck = common.correctTimeParams(this.startTime_problem, this.endTime_problem, 0);
		if (!timeCheck.status) {
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		let operaParam = this.getSelectedVAL();
		//		if(this.proTypeParams.problemType=='1'&&this.proTypeParams.problemClass=='1'){
		//			if(this.seneorPhenlist.length<1){
		//				this.jsonApiService.message('请确认添加传感器问题现象');
		//				return;
		//			}
		//		}
		if (this.proTypeParams.problemType == '1' && this.proTypeParams.problemClass == '1') {
			let sensor = $('#sensorPhenName').val();
			if (this.seneorPhenlist.length < 1 && !sensor && !this.proTypeParams.phenomenon) {
				this.jsonApiService.message('请确认添加传感器问题现象');
				return;
			}
			if (sensor && this.proTypeParams.phenomenon) {
				let phen = this.proSlectedItem.childs[+this.proTypeParams.problemClass].phenomenon[+this.proTypeParams.phenomenon].name;
				let phenResult = '传感器' + sensor + '-' + phen;
				if (this.seneorPhenlist.length < 1) {
					operaParam.resultPhenStr = phenResult;
				}
				else {
					let findIndex = operaParam.resultPhenStr.indexOf(phenResult)
					if (findIndex < 0) {
						operaParam.resultPhenStr = operaParam.resultPhenStr + ',' + phenResult;
					}
				}

			}
		}
		if (!this.proTypeParams.problemType || !this.proTypeParams.problemClass) {
			this.jsonApiService.message('请选择问题分类');
			return;
		}
		let proType = (+this.proTypeParams.problemType + 1) + '0' + (+this.proTypeParams.problemClass + 1);
		if (operaParam.resultPhenStr == '') {
			this.jsonApiService.message('问题现象不能为空');
			return;
		}

		let params = {
			programType: proType,
			deviceId: this.deviceId,             			//编号
			carNumber: this.carNumber || this.carNumberWeight.split(' ')[0],						//车牌,地磅车牌，哪个有数据显示哪个
			faultTypeName: operaParam.problemClassStr,		//故障类型
			faultTime: this.startTime_problem,               //故障时间
			faultPhenomenon: operaParam.resultPhenStr,	    //故障现象:例  传感器1-平直
			isPush: this.isPush,								//是否推送
			repairedGuide: operaParam.repairGuideStr,		//维修指导
			repairedRecords: '',								//维修记录
			repairedStatus: '',				                //维修状态(故障状态)
			repairedTime: '',								//维修时间
			repairedUser: '',								//维修人员
			remark: '',										//备注
			repairedConclusion: '',							//维修总结
		}

		let reqdata = '';
		for (let keys in params) {
			reqdata = reqdata + keys + '=' + params[keys] + '&';
		}
		reqdata = reqdata.substring(0, reqdata.length - 1);
		this.jsonApiService.http('deviceRepaired/validateRecord.html', 'deviceId=' + this.deviceId).subscribe(result => {
			if (result.valid) {
				this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
					this.jsonApiService.http('deviceRepaired/insertDeviceRepaired.html', reqdata).subscribe(result => {
						this.jsonApiService.message(result.message)
						if (result.success) {
							//							this.load();
						}
					})
				})
			} else {
				this.jsonApiService.http('deviceRepaired/insertDeviceRepaired.html', reqdata).subscribe(result => {
					this.jsonApiService.message(result.message)
					if (result.success) {
						//						this.load();
					}
				})
			}
		})
	}

	/**
	 * 记录传感器损坏模块开关
	 */
	sensorChannelChange() {
		this.sensorChannel = !this.sensorChannel;
		if (this.sensorChannel) {
			this.sensorLoad();
		}
	}
	/**
	 * 通道选择change事件,处理数据,记录选择通道 
	 */
	sensorChange(id, e) {
		if (e.target.checked) {
			this.sensorArr[id - 1].checked = true;
		} else {
			this.sensorArr[id - 1].checked = false;
		}
	}
	/*
	 * 记录传感器提交
	 */
	submitSensor() {
		if (!this.deviceId) {
			this.jsonApiService.message('请选择车辆');
			return
		}
		if (!this.startTime_sensor) {
			this.jsonApiService.message('请输入传感器损坏开始时间');
		}
		if (this.startTime_sensor && this.endTime_sensor) {
			let timeCheck = common.correctTimeParams(this.startTime_sensor, this.endTime_sensor, 0);
			if (!timeCheck.status) {
				this.jsonApiService.message(timeCheck.message);
				return;
			}
		}

		let channels: any = [];
		for (let item of this.sensorArr) {
			if (item.checked) {
				channels.push(item.id);
			}
		}
		if (!channels.length) {
			this.jsonApiService.message('请选择传感器通道');
			return;
		}
		let reqdata = {
			carNumber: this.carNumber,
			deviceId: this.deviceId,
			startTime: this.startTime_sensor,
			endTime: this.endTime_sensor,
			channels: channels.join(',')
		}
		this.jsonApiService.http_obj('sensorMarkDamage/addSensorMarkDamage.html', reqdata).subscribe(result => {
			this.jsonApiService.message(result.message)
			if (result.success) {
				this.sensorLoad();
			}
		})
	}
	/**
	 * 单个设备传感器损坏记录
	 */
	sensorLoad() {
		if (!this.deviceId) {
			this.jsonApiService.message('请选择车辆');
			return
		}
		let data = {
			pageSize: 20,
			nowPage: 1,
			parameters: {
				deviceId: this.deviceId
			}
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("sensorMarkDamage/sensorMarkDamageForPage.html", reqdata).subscribe(data => {
			if (data.isSuccess) {
				this.sensorTableData = data.exhibitDatas;
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	/*
	 * 传感器损坏记录删除
	 */
	delRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			this.jsonApiService.http_obj("sensorMarkDamage/deleteSensorMarkDamage.html", { id: row.id }).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.sensorLoad();
				}
			})
		})
	}
	/**
	 * 设备电压信息开关,this.voltage为true显示,false隐藏
	 */
	voltageChange() {
		if (this.voltage) {
			this.dealVoltageData();
		} else {
			let len = this.passageData.length;
			for (var i = 0; i < len; i++) {
				if (this.passageData[i].name === '设备电压 (v)') {
					this.passageData.splice(i, 1);
					break;
				}
			}
		}
		this.echartOption.series = this.passageData;
		this.myChart.setOption(this.echartOption, true);
	}
	/**
	 * 电压采样半小时一个点,对电压数据值进行补点,处理成和历史数据X轴点数对应;
	 * 补点原理:电压两点之前补前面一个点的值,电压最后一个点之后,补最后一个点值;
	 */
	dealVoltageData() {
		this.voltageDataEchart = [];
		var index = 0;
		var volIndex = 0;
		for (var i = 0; i < this.voltageData.length - 1; i++) {
			var temTime1 = common.mmsstoTimestamp(this.voltageData[i].uploadDate);
			var temTime2 = common.mmsstoTimestamp(this.voltageData[i + 1].uploadDate);
			for (var j = index; j < this.allData.length - 1; j++) {
				var temTime3 = common.mmsstoTimestamp(this.allData[j].uploadDate);
				var temTime4 = common.mmsstoTimestamp(this.allData[j + 1].uploadDate);
				index = j;
				volIndex = i;
				if (temTime3 >= temTime1 && temTime2 >= temTime3) {                //两点之间补点
					this.voltageDataEchart.push(this.voltageData[i].voltage);
				} else if (temTime3 < temTime1) {									//电压最后一点在数据范围之外后,该点之前补点,补上一个点
					this.voltageDataEchart.push(this.voltageData[i - 1].voltage)
				} else if (temTime3 > temTime2 && i < this.voltageData.length - 2) {	//最后一个点之前跳出循环
					if (temTime1 >= this.allData[0]) {
						if (temTime4 - temTime3 > temTime2 - temTime1) {//处理电压连续两点差值小于历史数据两点差值
							this.voltageDataEchart.push(this.voltageData[i].voltage);
							break;
						}
					} else {
						break;
					}
				} else {
					this.voltageDataEchart.push(this.voltageData[i].voltage)
				}
			}
		}
		if (this.allData.length - this.voltageDataEchart.length == 1) {  //处理最一点的值
			this.voltageDataEchart.push(this.voltageData[volIndex].voltage);
		}
		if (this.voltageData.length >= 1) {
			let obj = {
				name: '设备电压 (v)',
				type: 'line',
				yAxisIndex: 0,
				show: true,
				data: this.voltageDataEchart,
				itemStyle: {
					color: 'orange'
				}
			};
			this.passageData.push(obj);
		}
	}

	/**
	 * 设备详细    导航tab切换 
	 */
	tableDataTab1: any = [];
	tableDataTab2: any = [];
	tableDataTab2_1: any = [];
	tableDataTab3: any = [];
	tableDataTab4_1: any = [];
	tableDataTab4_2: any = [];
	tableDataTab5: any = [];
	tableDataTab6: any = [];
	tableDataTab7: any = [];		//磅单数据
	totalCountTab: number = 0;
	pageSizeTab: number = 10;
	curPageTab: number = 1; //分页当前页
	activeTab: string = '';
	btnGroupActive: string = '5';//快捷时间按钮(默认三个月);
	btnGroupActiveText: string = '近三个月';//快捷时间按钮文字
	startDateBtn: string = '';
	endDateBtn: string = '';
	/**
	 * 时间快捷选择方式:一周/半个月/一个月/两个月/三个月 
	 */
	selectTimeFast(val) {
		this.btnGroupActive = val;
		let temDate = new Date();
		switch (val) {
			case '1':
				this.btnGroupActiveText = '近一周';
				temDate.setDate(temDate.getDate() - 7);//近一周
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			//			case '2':
			//				this.btnGroupActiveText = '近半个月';
			//				temDate.setDate(temDate.getDate() - 15);//近半个月
			//				this.startDateBtn = common.getTimeMmss(temDate);
			//				this.endDateBtn = common.getNowTime();
			//				break;
			case '3':
				this.btnGroupActiveText = '近一个月';
				temDate.setMonth(temDate.getMonth() - 1);//近一个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			//			case '4':
			//				this.btnGroupActiveText = '近两个月';
			//				temDate.setDate(temDate.getDate() - 60);//近两个月
			//				this.startDateBtn = common.getTimeMmss(temDate);
			//				this.endDateBtn = common.getNowTime();
			//				break;
			case '5':
				this.btnGroupActiveText = '近三个月';
				temDate.setMonth(temDate.getMonth() - 3);//近三个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			case '6':
				this.btnGroupActiveText = '近半年';
				temDate.setMonth(temDate.getMonth() - 6);//近半年
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
			case '7':
				this.btnGroupActiveText = '全部';
				// temDate.setFullYear(temDate.getFullYear() - 1);//近一年
				this.startDateBtn = '2017-01-01 00:00:00';
				this.endDateBtn = common.getNowTime();
				break;
			default:
				this.btnGroupActive = '5';
				this.btnGroupActiveText = '近三个月';
				temDate.setDate(temDate.getDate() - 90);//默认近三个月
				this.startDateBtn = common.getTimeMmss(temDate);
				this.endDateBtn = common.getNowTime();
				break;
		}
		this.getDeviceInfoData();
		this.getTableDataTab(this.activeTab);
	}
	getTabData(type) {
		this.tableDataTab1 = [];
		this.tableDataTab2 = [];
		this.tableDataTab2_1 = [];
		this.tableDataTab3 = [];
		this.tableDataTab3 = [];
		this.tableDataTab4_1 = [];
		this.tableDataTab4_2 = [];
		this.tableDataTab5 = [];
		this.tableDataTab6 = [];
		this.tableDataTab7.length = 0;
		this.totalCountTab = 0;
		this.pageSizeTab = 10;
		this.curPageTab = 1;
		this.activeTab = type;
		this.getTableDataTab(type);
	}
	//获取数据:故障信息/维修信息/警报信息/数据修复/固件升级/系数设置
	versionUpdataCount: number;
	coefUpdataCount: number;
	fix: any = {
		totalCount: 0,
		mainCount: 0,
		sensorCount: 0,
		lineCount: 0,
		gpsCount: 0,
		mainQuestion: 0,
		sensorQuestion: 0,
		lineQuestion: 0,
		gpsQuestion: 0,
		firstFixQuestion: '',
		firstFixQuestionTime: '',
		firstSensorQuestion: '',
		firstSensorQuestionTime: '',
		lastSensorQuestion: '',
		lastSensorQuestionTime: '',
		lastGPSQuestion: '',
		lastGPSQuestionTime: '',
	}
	timelineDate: any = [];
	getTableDataTab(type) {
		let reqData: any, param: any;
		switch (type) {
			case '':
				this.getDeviceInfoData();
				break;
			case '1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.deviceId,
						carNumber: this.selectRowData.carNumber,
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('dataExceptionRecord/dataRecordPage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						item.useTypeL1 = this.getUseTypeNameL1(item.useTypeL1);
						item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
						item.exceptionType = this.getExceptionTypeName(item.exceptionType);
						item.programType = this.getProgramTypeName(item.programType);
						if (item.coefficient) {
							let coefArr = [];
							for (let i = 0; i < item.coefficient.length; i++) {
								let _item = item.coefficient[i];
								if (_item && _item != '0') {
									var obj = {
										value: item.coefficient[i],
										index: i + 1
									}
									coefArr.push(obj);
								}
							}
							item.coef = coefArr;
						} else {
							item.coef = [];
						}
					}
					this.tableDataTab1 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '2':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						searchKey: this.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('fixdatalog/logforpage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab2 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '2_1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						searchKey: this.deviceId,
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
						status: "0",
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('exceptionOrderForHaiLuo/findExceptionOrderList.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab2_1 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '3':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('alertlog/deviceShutDownAlarm.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					if (type == '3') {
						for (let item of result.exhibitDatas) {
							item.totalSecond = common.secondToDate(item.totalSecond);
						}
					}
					this.tableDataTab3 = result.exhibitDatas;
					this.totalCountTab = result.recordCount;
				})
				break;
			case '4_1':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.deviceId,
						repairedStatus: '0',
						dateType: '1',
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceRepaired/findDeviceRepairedList.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab4_1 = result.exhibitDatas || [];
					this.tableDataTab4_1.map(item => item.callDuration = common.secondToDate(item.callDuration));
					this.totalCountTab = result.recordCount;
				})
				break;
			case '4_2':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.deviceId,
						sortType: '2',
						startDate: this.startDateBtn,
						endDate: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceRepairedV2/findDeviceRepairedV2List.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab4_2 = result.exhibitDatas || [];
					for (let item of this.tableDataTab4_2) {
						var faultPhenomenonList = item.faultPhenomenonList && Array.from(new Set(item.faultPhenomenonList));
						item.faultPhenomenonList = faultPhenomenonList.length > 0 ? faultPhenomenonList.join(",") : '';

						var repairContentList = item.repairContentList && Array.from(new Set(item.repairContentList));
						item.repairContentList = repairContentList.length > 0 ? repairContentList.join(",") : '';

						var repairSubdivideList = item.repairSubdivideList && Array.from(new Set(item.repairSubdivideList));
						item.repairSubdivideList = repairSubdivideList.length > 0 ? repairSubdivideList.join(",") : '';

						item.useTypeL2 = this.getUseTypeNameL2(item.useTypeL2);
					}
					this.totalCountTab = result.recordCount;
					this.repairedDeviceInfo.fixedCount = result.recordCount;
				})
				break;
			case '5':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('log/upgrade.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					this.tableDataTab5 = result.exhibitDatas || [];
					this.totalCountTab = result.recordCount;
				})
				break;
			case '6':
				reqData = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						deviceId: this.deviceId,
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
					}
				}
				param = 'gridPager=' + JSON.stringify(reqData);
				this.jsonApiService.http('deviceCoefLog/deviceCoefLogforpage.html', param).subscribe(result => {
					if (!result.isSuccess) {
						this.jsonApiService.message(result.message);
						return;
					}
					for (let item of result.exhibitDatas) {
						if (item.newCoef) {
							let newCoef = [];
							for (let i = 0; i < item.newCoef.length; i++) {
								let _item = item.newCoef[i];
								if (_item) {
									let obj: any = {
										value: item.newCoef[i],
										index: i + 1
									}
									newCoef.push(obj);
								}
							}
							item.newCoef = newCoef;
						} else {
							item.newCoef = [];
						}

						if (item.oldCoef) {
							let oldCoef = [];
							for (let i = 0; i < item.oldCoef.length; i++) {
								let _item = item.oldCoef[i];
								if (_item) {
									let obj: any = {
										value: item.oldCoef[i],
										index: i + 1
									}
									oldCoef.push(obj);
								}
							}
							item.oldCoef = oldCoef;
						} else {
							item.oldCoef = [];
						}

					}
					this.tableDataTab6 = result.exhibitDatas || [];
					this.totalCountTab = result.recordCount;
				})
				break;
			case '7':
				let reqdata: any = {
					pageSize: this.pageSizeTab,
					nowPage: this.curPageTab,
					parameters: {
						companyId: this.selectedCompanyId,
						carNumber: this.carNumber || this.carNumberWeight.split(' ')[0],
						startTime: this.startDateBtn,
						endTime: this.endDateBtn,
						deviceId: this.deviceId
					}
				}
				reqdata = 'gridPager=' + JSON.stringify(reqdata);
				this.jsonApiService.http("weighbridge/list.html", reqdata).subscribe(data => {
					this.tableDataTab7 = data.exhibitDatas;
					this.totalCount = data.recordCount;
				})
				break;
			case '8':
				this.addHostAndSensor() //主机和传感器
				// reqData = 'deviceId=' + this.deviceId;
				// this.jsonApiService.http("eventMonitor/eventDataList.html", reqData).subscribe(data => {
				// 	if (data.success && data.data) {
				// 		this.coefUpdataCount = 0;
				// 		this.versionUpdataCount = 0;
				// 		this.fix = {
				// 			totalCount: 0,
				// 			mainCount: 0,
				// 			sensorCount: 0,
				// 			lineCount: 0,
				// 			gpsCount: 0,
				// 			mainQuestion: 0,
				// 			sensorQuestion: 0,
				// 			lineQuestion: 0,
				// 			gpsQuestion: 0,
				// 			firstFixQuestion: '',
				// 			firstFixQuestionTime: '',
				// 			firstSensorQuestion: '',
				// 			firstSensorQuestionTime: '',
				// 			lastSensorQuestion: '',
				// 			lastSensorQuestionTime: '',
				// 			lastGPSQuestion: '',
				// 			lastGPSQuestionTime: '',
				// 		}
				// 		let result = data.data;
				// 		let sensorObj = {}
				// 		for (let item of result) {
				// 			item.eventType1 == 4 ? this.coefUpdataCount += 1 : this.coefUpdataCount = this.coefUpdataCount;
				// 			item.eventType1 == 3 ? this.versionUpdataCount += 1 : this.versionUpdataCount = this.versionUpdataCount;
				// 			item.eventType2 != 0 ? this.fix.totalCount += 1 : this.fix.totalCount = this.fix.totalCount;
				// 			item.eventType2Name == '更换主机' ? this.fix.mainCount += 1 : this.fix.mainCount = this.fix.mainCount;
				// 			item.eventType2Name == '更换传感器' ? this.fix.sensorCount += 1 : this.fix.sensorCount = this.fix.sensorCount;
				// 			item.eventType2Name == '更换线材' ? this.fix.lineCount += 1 : this.fix.lineCount = this.fix.lineCount;
				// 			item.eventType2Name == '更换GPS' ? this.fix.gpsCount += 1 : this.fix.gpsCount = this.fix.gpsCount;
				// 			if (item.eventType2 != 0) {
				// 				item.eventType2 == 202 ? this.fix.firstFixQuestion = null : this.fix.firstFixQuestion = item.eventContent;
				// 				this.fix.firstFixQuestionTime = item.eventTime;
				// 			}
				// 			if (item.eventType2 == 202) {
				// 				this.fix.firstSensorQuestion = item.eventContent;
				// 				this.fix.firstSensorQuestionTime = item.eventTime;
				// 				// 增加传感器问题列表
				// 				let arr = item.eventContent.split("-")
				// 				if (arr.length > 1) {
				// 					// 切分出管道号
				// 					let channel = arr[arr.length - 1]
				// 					item.text1 = "第一次维修CH" + channel
				// 					item.text2 = "第一次维修CH" + channel + "时间"
				// 					if (sensorObj[channel]) {
				// 						// 同一管道只保留最新的数据
				// 						let oldTime = sensorObj[channel].eventTime.replace(/-/g, "/");
				// 						let newTime = item.eventTime.replace(/-/g, "/");
				// 						if (new Date(oldTime).valueOf() > new Date(newTime).valueOf()) {
				// 							sensorObj[channel] = item
				// 						}
				// 					} else {
				// 						sensorObj[channel] = item
				// 					}
				// 				}

				// 			}
				// 			if (item.eventType2 == 202 && !this.fix.lastSensorQuestion) {
				// 				this.fix.lastSensorQuestion = item.eventContent;
				// 				this.fix.lastSensorQuestionTime = item.eventTime;
				// 			}
				// 			if (item.eventType2 == 204 && !this.fix.lastGPSQuestion) {
				// 				this.fix.lastGPSQuestion = item.eventContent;
				// 				this.fix.lastGPSQuestionTime = item.eventTime;
				// 			}
				// 		}
				// 		// 传感器对象进行排序并变成数组的格式
				// 		let sensorArr = (Object.keys(sensorObj)).reduce(function (arr: any, k) {
				// 			arr.push(sensorObj[k])
				// 			return arr
				// 		}, [])
				// 		// 给页面的变量赋值
				// 		this.sensorList = sensorArr.sort(function (a, b) {
				// 			let oldTime = a.eventTime.replace(/-/g, "/");
				// 			let newTime = b.eventTime.replace(/-/g, "/");
				// 			if (new Date(oldTime).valueOf() < new Date(newTime).valueOf()) {
				// 				return -1
				// 			}
				// 		})

				// 		var year = new Date().getFullYear();
				// 		let obj: any;
				// 		this.timelineDate = [];
				// 		for (let i = 2015; i < year + 1; i++) {
				// 			let chrildArr: any = [];
				// 			obj = null;
				// 			for (let item of result) {
				// 				if (item.eventYear == i) {
				// 					chrildArr.push(item);
				// 					obj = {
				// 						date: item.eventYear + '',
				// 						chrild: chrildArr,
				// 						isShow: true,
				// 					}
				// 				}
				// 			}
				// 			if (obj) {
				// 				this.timelineDate.push(obj)
				// 			}
				// 		}
				this.timelineDate = this.timelineDate.reverse();
				if (this.deviceBaseInfo.inputDate) {
					this.deviceBaseInfo.installTime = common.secondToDate((common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceBaseInfo.inputDate)) / 1000)
				}
				// 获取其他的数据接口
				this.jsonApiService.http_obj("system/getRealTimeData.html", { deviceId: this.deviceId }).subscribe(data => {
					this.otherData = data.data
				})
				// 	}
				// })
				break;
			default:
				this.getDeviceInfoData();
				break;

		}
	}
	/**
   * 设备事件 新增主机生命周期和传感器生命周期
   */
	hostTableData: any = [] //主机table列表
	sensorListData: any = [] //传感器table列表
	sensorCount: string = '' //传感器数量
	addHostAndSensor() {
		this.jsonApiService.http_get('matterReplaceInfo/queryMatterReplaceInfoListByDeviceId.html?deviceId=' + this.deviceId).subscribe(data => {
			if (data.success && data.data) {
				let result = data.data
				this.hostTableData = result.hostList || []
				this.sensorListData = result.sensorList ? this.mergeData(result.sensorList, "materielNumber") : []
				this.sensorCount = result.sensorCount
			}
		})
	}
	mergeData(data, indexName) {
		if (data == undefined || data.length == 0 || data == null) {
			return;
		}
		let res = [] //结果数组
		let rowSpan = 1
		for (let i = 0; i < data.length; i++) {
			for (let j = i + 1; j < data.length; j++) {
				if (data[i][indexName] == data[j][indexName]) {
					rowSpan++;
				} else {
					break;
				}
			}
			//开始复制某组相同的数据
			if (rowSpan > 1) {
				for (let k = 0; k < rowSpan; k++) {
					data[k + i].secondIndex = k;
					data[k + i].rowSpan = rowSpan;
					res.push(data[k + i])
				}
				i += (rowSpan - 1) //跳过相同的数据
				rowSpan = 1;
			} else {
				//复制单独的数据
				data[i].secondIndex = 0;
				data[i].rowSpan = rowSpan;
				res.push(data[i])
			}
		}
		return res
	}
	refreshTab() {
		this.getTabData(this.activeTab);
	}
	//分页回调
	paginateTab(e) {
		this.curPageTab = e.page + 1;
		this.pageSizeTab = e.rows;
		this.getTableDataTab(this.activeTab);
	}
	//根据编码映射对应车辆类型名称
	getUseTypeNameL1(key) {
		if (key) {
			return this.TcarUseList[key];
		} else {
			return '';
		}
	}
	//根据编码映射对应车辆类型名称
	getUseTypeNameL2(key) {
		if (key) {
			return this.TcarDeatailUseList[key];
		} else {
			return '';
		}
	}
	//问题分类
	getExceptionTypeName(key) {
		if (key) {
			return this.questionNameList[key];
		} else {
			return '';
		}
	}
	//现象分类
	getProgramTypeName(key) {
		if (key) {
			return this.questionDeatailNameList[key];
		} else {
			return '';
		}
	}
	questionNameList: any = {
		'1': '算法问题',
		'2': '硬件问题',
		'3': '司机问题',
		'4': '对接问题',
		'5': '运维问题',
		'6': '安装问题'
	};
	questionDeatailNameList: any = {
		'100': '其他',
		'101': '上货问题',
		'102': '卸货问题',
		'103': '在途问题',
		'104': '多次上货',
		'105': '多次卸货',
		'200': '其他',
		'201': '主机问题',
		'202': '传感器问题',
		'203': 'GPS问题',
		'204': '线材问题',
		'300': '其他',
		'301': '司机问题',
		'400': '其他',
		'401': '对接问题',
		'500': '其他',
		'501': '运维问题',
		'601': '安装问题',
		'600': '其他'
	}
	TcarUseList = carTypeListObj.carUseList
	TcarDeatailUseList = carTypeListObj.carDeatailUseList
	algorithmQuestionList: any = [{
		exceptionType: '1',
		programType: '101',
		faultTypeName: '算法问题',
		text: '上货问题',
		selected: false
	}, {
		exceptionType: '1',
		programType: '104',
		faultTypeName: '算法问题',
		text: '多次上货',
		selected: false
	}, {
		exceptionType: '1',
		programType: '102',
		faultTypeName: '算法问题',
		text: '卸货问题',
		selected: false
	}, {
		exceptionType: '1',
		programType: '105',
		faultTypeName: '算法问题',
		text: '多次卸货',
		selected: false
	}, {
		exceptionType: '1',
		programType: '103',
		faultTypeName: '算法问题',
		text: '在途问题',
		selected: false
	}]
	/**
	 * 设备详细(设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	selectRowData: any = {
		companyName: '',
		companyId: '',
		deviceId: '',
		carNumber: '',
	};//选中数据查看的数据row
	deviceDetail() {
		if (!this.deviceId) {
			this.jsonApiService.message('请选择要查看的车辆');
			return;
		}
		$('#deviceDetailModal').show();
		$('.s-lis').removeClass('active');
		$('.tab-pane').removeClass('active');
		$('.s-lis').eq(0).addClass('active');
		$('.s-lis').eq(0).find('a').attr('aria-expanded', 'true');
		$('#all').eq(0).addClass('active');
		this.btnGroupActive = '5'
		let temDate = new Date();
		temDate.setDate(temDate.getDate() - 90);//默认近三个月
		this.startDateBtn = common.getTimeMmss(temDate);
		this.endDateBtn = common.getNowTime();
		this.getDeviceInfoData();
		this.getTableDataTab('7');	//渲染磅单表格
	}
	/**
	 * 关闭设备详情弹窗 
	 */
	cancelDeviceDetail() {
		$('#deviceDetailModal').hide();
	}
	tableMove() {
		$('body').delegate('#headDrag', 'mousedown', function (e) {
			$(this).css("cursor", "move");
			var offset = $('#deviceDetailModal').position();
			var x = e.pageX - offset.left;
			var y = e.pageY - offset.top;
			$(document).bind("mousemove", function (ev) {
				$("#deviceDetailModal").stop();
				var _x = ev.pageX - x;
				var _y = ev.pageY - y;
				if (_y < 0) { //避开头部横条
					return;
				}
				$("#deviceDetailModal").animate({ left: _x + "px", top: _y + "px" }, 2);
			});
		});
		$(document).mouseup(function () {
			//	        $(".hold-all").css("cursor","default"); 
			$("#deviceDetailModal").css("cursor", "default");
			$(this).unbind("mousemove");
		});
		//      $('body').delegate('.hold-title','mousedown',function(e){
		//          $(this).css("cursor","move");
		//          var offset = $('.hold-all').position();
		//          var x = e.pageX - offset.left;
		//          var y = e.pageY - offset.top;
		//          console.log(offset.left,'========offset.left=======')
		//          console.log(x,'========xxxx=======')
		//          $(document).bind("mousemove",function(ev){ 
		//              $(".hold-all").stop();
		//              var _x = ev.pageX - x;
		//              var _y = ev.pageY - y;
		//              $(".hold-all").animate({left:_x+"px",top:_y+"px"},2);  
		//          });  
		//      });
	}
	/**
	 * 获取设备信息 (设备基本信息/故障信息/维修信息/警报信息/数据修复)
	 */
	deviceBaseInfo: any = {
		companyName: '',
		carNumber: '',
		deviceId: '',
		hwVersion: '',
		useTypeL1: '',
		useTypeL2: '',
		userTypeName: '',
		sensorType: '',
		productNo: '',
		iccid: '',
		driverName: '',
		phone: '',
		inputDate: '',
		userNameForCreate: '',
		sensorChannel: [],
		coef: [],
		coefT: [],
		version: ''
	};
	questionRecordInfo: any = [];//问题记录
	questionRecordTotal: number = 0;//问题记录总和
	dataFixInfo: any = {};//数据修复
	alertDataInfo: any = {};//警报数据
	repairedDeviceInfo: any = {};//维修记录
	deviceRealTimeDataInfo: any = {};//设备实时数据
	isShowGPSAlert: boolean = false;//是否显示GPS数据更新异常警报提示
	isShowOfflineAlert: boolean = false;//是否显示离线警报提示
	offlineDiffTime: string = '';//离线时长
	weightCount: number = 0;//过磅次数

	weightData: any = {		//总磅单数
		'WeightBridgeCount': '',
		'weight': '',
		'lastDate': '',
	}

	initDeviceBaseInfo() {
		this.deviceBaseInfo = {
			companyName: '',
			carNumber: '',
			deviceId: '',
			hwVersion: '',
			useTypeL1: '',
			useTypeL2: '',
			userTypeName: '',
			sensorType: '',
			productNo: '',
			iccid: '',
			driverName: '',
			phone: '',
			inputDate: '',
			userNameForCreate: '',
			sensorChannel: [],
			coef: [],
			coefT: [],
			version: ''
		};
		this.isShowGPSAlert = false;
		this.isShowOfflineAlert = false;
		this.questionRecordInfo = [];
		this.questionRecordTotal = 0;
		this.dataFixInfo = {};
		this.alertDataInfo = {};
		this.repairedDeviceInfo = {};
		this.deviceRealTimeDataInfo = {};
		this.offlineDiffTime = '';
		this.weightCount = 0;
	}
	getDeviceInfoData() {
		this.initDeviceBaseInfo();
		//设备基本信息
		this.jsonApiService.http_obj("system/getDeviceBaseInfoByDeviceId.html", { deviceId: this.deviceId }).subscribe(data => {
			if (data.success && data.data) {
				for (let item in this.deviceBaseInfo) {
					if (item === 'coef' || item === 'coefT' || item === 'sensorChannel') {
						this.deviceBaseInfo[item] = data.data[item] || [];
					} else {
						this.deviceBaseInfo[item] = data.data[item] || '';
					}
				}
				this.deviceBaseInfo.userTypeName = this.getUseTypeNameL2(this.deviceBaseInfo.useTypeL2);
				if (this.deviceBaseInfo.coef) {
					let coefArr = [];
					for (let i = 0; i < this.deviceBaseInfo.coef.length; i++) {
						let _item = this.deviceBaseInfo.coef[i];
						if (_item) {
							let obj: any = {
								value: _item,
								index: i + 1
							}
							coefArr.push(obj);
						}
					}
					this.deviceBaseInfo.coefT = coefArr;
				} else {
					this.deviceBaseInfo.coefT = [];
				}
			}

		})
		//问题统计(近三个月)
		this.jsonApiService.http_obj("system/countDeviceDataRecordByDeviceId.html", { deviceId: this.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.questionRecordTotal = 0;
				this.questionRecordInfo = data.data;
				for (let item of this.questionRecordInfo) {
					this.questionRecordTotal += +item.reasonCount;
				}
			}
		})
		//数据修复统计(近三个月)
		this.jsonApiService.http_obj("system/queryDataFixCountByDeviceId.html", { deviceId: this.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.dataFixInfo = data.data;
			}
		})
		//警报统计(近三个月)
		this.jsonApiService.http_obj("system/queryAlarmCountByDeviceId.html", { deviceId: this.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.alertDataInfo = data.data;
			}
		})
		//维修记录统计(近三个月)
		this.jsonApiService.http_obj("system/queryDeviceRepairedByDeviceId.html", { deviceId: this.deviceId, startDate: this.startDateBtn, endDate: this.endDateBtn }).subscribe(data => {
			if (data.success && data.data) {
				this.repairedDeviceInfo = data.data;
			}
		})
		//设备状态(实时数据)
		let deviceId = this.deviceId;
		this.jsonApiService.http_obj("system/getRealTimeData.html", { deviceId: this.deviceId }).subscribe(data => {
			if (data.success && data.data) {
				this.deviceRealTimeDataInfo = data.data;
				let carUploadDate, gpsUploadDate;
				if (this.deviceRealTimeDataInfo.carUploadDate) {
					carUploadDate = this.deviceRealTimeDataInfo.carUploadDate;
				}
				if (this.deviceRealTimeDataInfo.gpsUploadDate) {
					gpsUploadDate = this.deviceRealTimeDataInfo.gpsUploadDate;
				}
				if (gpsUploadDate && carUploadDate) {
					let abs = Math.abs(common.mmsstoTimestamp(carUploadDate) - common.mmsstoTimestamp(gpsUploadDate));
					abs >= 30 * 60 * 1000 ? this.isShowGPSAlert = true : this.isShowGPSAlert = false; //计算GPS是否异常:更新时间 - gps更新时间  > 30分钟    =>GPS异常
					this.getWeighbridge(deviceId);
				}
			}
		})
		// 总磅单数（近三个月）
		const reqDate = {
			'deviceId': this.deviceId,
			'startDate': this.startDateBtn,
			'endDate': this.endDateBtn,
		}
		this.jsonApiService.http_obj("system/queryWeightBridgeByDeviceId.html", reqDate).subscribe(result => {
			if (result.success) {
				this.weightData = result.data;
			}
		});
	}
	//获取磅单数据:用于判断离线异常
	getWeighbridge(deviceId) {
		this.jsonApiService.http_obj("weighbridge/weightforreal.html", { deviceId: deviceId, startTime: this.deviceRealTimeDataInfo.updateTime, endTime: common.getNowTime() }).subscribe(data => {
			if (data.success && data.data) {
				this.weightCount = 0;
				if (this.deviceRealTimeDataInfo.updateTime) {
					let diffTiem = common.mmsstoTimestamp(common.getNowTime()) - common.mmsstoTimestamp(this.deviceRealTimeDataInfo.updateTime);
					this.offlineDiffTime = common.secondToDate(diffTiem / 1000);//计算离线时长:当前时间 - 最后更新时间
					let weightData = data.data;
					for (let item of weightData) {
						if (+item.weight > 0) {
							this.isShowOfflineAlert = true;
							this.weightCount += 1;//计算榜单数
						}
					}
				}
			}
		})
	}
	/**
	 * 问题记录跳转
	 */
	jumpQuestionByHand(type1, type2, value) {
		if (value == 'total') {
			$('#myTab').find('li.s-lis').removeClass('active').find('.reqRecord').parent('li.s-lis').addClass('active');
			$('#all').removeClass('active');
			$('#question').addClass('active');
			this.getTabData('1');
			return false;
		}

		if (value == 0) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			exceptionType: type1,
			programType: type2
		}
		this.router.navigate(['/abnormal-alert/artificialMonitor']);
		common.setCookie('jumpQuestionByHandList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	/**
	 * 设备警报跳转
	 */
	jumpAlertDataList(type, value) {
		if (value == 'total') {
			this.getTabData('3');
			$('#myTab').find('li.s-lis').removeClass('active').find('.alertRecord').parent('li.s-lis').addClass('active');
			$('#all').removeClass('active');
			$('#alert').addClass('active');
			return false;
		}

		if (!value) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			type: type,
		}
		this.router.navigate(['/abnormal-alert/device-off']);
		common.setCookie('jumpAlertDataList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	/**
	 * 设备维修跳转
	 */
	jumpRepairedDeviceList(type, dateType, value) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			repairedStatus: type,
			dateType: dateType,
		}
		if (type == '0') {
			this.router.navigate(['/device-management/fault']);
		} else if (type == '1') {
			this.router.navigate(['/device-management/faultV2']);
		}
		common.setCookie('jumpRepairedDeviceList', JSON.stringify(queryParams));
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)
	}
	jumpDataFixList(type, value) {
		if (!value) { this.jsonApiService.message('无记录!'); return };
		$('#deviceDetailModal').hide();
		let queryParams = {
			companyName: this.selectRowData.companyName,
			companyId: this.selectRowData.companyId,
			deviceId: this.selectRowData.deviceId,
			carNumber: this.selectRowData.carNumber,
			startTime: this.startDateBtn,
			endTime: this.endDateBtn,
			type: null
		}
		switch (type) {
			case '1':
				queryParams.type = '1';
				this.router.navigate(['/log-info/repairRecord']);
				common.setCookie('jumpDataFixList', JSON.stringify(queryParams));
				break;
			case '2':
				queryParams.type = '2';
				this.router.navigate(['/log-info/repairRecord']);
				common.setCookie('jumpDataFixList', JSON.stringify(queryParams));
				break;
			case '3':
				queryParams.type = '0';
				this.router.navigate(['/abnormal-alert/order']);
				common.setCookie('jumpExceptionOrderList', JSON.stringify(queryParams));
				break;
			default:
				break;
		}
		setTimeout(function () {
			$('#left-panel').find('.top-menu-invisible.open').find('.UL').css('display', 'none');
			$('#left-panel').find('.top-menu-invisible.open').removeClass('open');
			$('#left-panel').find('.top-menu-invisible.active').addClass('open');
			$('#left-panel').find('.top-menu-invisible.active').find('.UL').css('display', 'block');
		}, 350)

	}



	/**
	 *  有磅单车辆查询模块
	 */
	deleteCarFlag: any = '';//删除标识
	carWeightList: any = [];//地磅数据车辆
	carNumberWeight: string = '';//地磅数据车辆车牌
	clearEventFlag: boolean = false;//清除子组件上下键盘事件
	// 榜单select2
	//拉取车辆数据
	selectLoadometer() {
		var that = this;
		$("#loadometerSelect").select2({
			language: "zh-CN",
			placeholder: "请选择",
			allowClear: true,
			templateResult: this.formatRepo
		}).on("select2:select", function (e) {
			that.clearEventFlag = true;
			that.keyCodeEvent();
			if (that.carNumber) {
				that.deleteCarFlag = new Date().getTime();
			}
			var data = e.params.data;
			setTimeout(() => { that.deviceId = data.id; }, 100)

			that.carNumberWeight = data.text;
			let len = that.carList.length;
			if (len > 1) {
				for (let x = 0; x < len; x++) {
					if (that.carNumberWeight == that.carList[x].text) {
						that.carIndexMsg = {
							allNums: len,
							index: (x + 1),
							status: true,
						}
						break;
					}
				}
			} else {
				that.carIndexMsg.status = false;
			}
		});
	}
	//公司id拉取车辆
	queryCarListByCompanyId() {
		// this.deviceId = '';
		// this.carNumber = '';
		// this.isAllowNext = false;
		// this.isAllowPre = false;
		this.carIndexMsg.status = false;
		let reqdata = {
			'companyId': this.selectedCompanyId,
			'startTime': this.startTime,
			'endTime': this.endTime
		}
		this.jsonApiService.http_obj("weighbridge/queryCarNumberWeightBridgeDownList.html", reqdata).subscribe(data => {
			var carlist = data.data;
			var selectdata = [];
			for (var i = 0; i < carlist.length; i++) {
				var obj = {
					id: carlist[i].deviceId,
					text: carlist[i].carNumber + ' [' + carlist[i].count + ']',
				}
				selectdata[i] = obj;
			}
			this.carList = selectdata;
			var selectObj = $("#loadometerSelect");
			this.clearSelect2(selectObj); //清除Select中的数据
			selectObj.select2({
				language: "zh-CN",
				data: selectdata, //为Select添加数据
				templateResult: this.formatRepo
			})
		})
	}
	//select2 格式回调函数
	formatRepo(state) {
		if (!state.id) {
			return state.text;
		}
		var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	clearSelect2(obj) {
		obj.empty();
		obj.prepend("<option value=''>请选择</option>");
	}
	//擦除车牌号码所选值
	del_loadometer() {
		this.deviceId = '';
		this.carNumberWeight = '';
		this.carIndexMsg.status = false;
		if (this.companyId) {
			this.queryCarListByCompanyId();
		} else {
			//采用简单粗暴的方法清除;官方推荐的方法失效
			var str = $("<span class='select2-selection__placeholder'>请选择</span>");
			$('#loadometerSelect').val("");
			$("#select2-loadometerSelect-container").empty();
			$("#select2-loadometerSelect-container").attr("title", "");
			$("#select2-loadometerSelect-container").prepend(str);
		}
	}
	//selcet2  车辆
	nextCarLoad(type) {
		this.isAllowNext = false;
		this.isAllowPre = false;
		//		this.isDisable = true;
		if (this.carList.length > 1 && this.deviceId) {
			let len = this.carList.length;
			for (let i = 0; i < len; i++) {
				if (this.carList[i].text === this.carNumberWeight && this.carList[i].id === this.deviceId) {
					if (type === 'pre') {
						if (i > 0) {

							this.carNumberWeight = this.carList[i - 1].text;
							this.deviceId = this.carList[i - 1].id;
							$('#loadometerSelect').val(this.deviceId).trigger('change');
							break;
						} else {
							this.isAllowPre = true;
							break;
						}
					} else if (type === 'next') {
						if (i < len - 1) {
							this.carNumberWeight = this.carList[i + 1].text;
							this.deviceId = this.carList[i + 1].id;
							$('#loadometerSelect').val(this.deviceId).trigger('change');
							break;
						} else {
							this.isAllowNext = true;
							break;
						}
					}
				}
			}
			for (let x = 0; x < len; x++) {
				if (this.carNumberWeight == this.carList[x].text) {
					this.carIndexMsg = {
						allNums: len,
						index: (x + 1),
						status: true,
					}
					break;
				}

			}
		}
	}
	// 验证地磅编辑弹出层
	validatorOptions = {
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			carNumber: {
				validators: {
					notEmpty: {
						message: '请输入车牌号码'
					}
				}
			},
			uploadDate: {
				validators: {
					notEmpty: {
						message: '请输入称重过磅时间'
					}
				}
			},
		}

	};
	// 地磅编辑数据
	totalCount: any;
	handleRow = {
		carNumber: "",
		deviceId: "",
		id: "",
		review: "",
		taskId: "",
		date: "",
		weight: "",
	};
	//分页回调
	paginate(e) {
		this.curPageTab = e.page + 1;
		this.pageSizeTab = e.rows;
		this.getTableDataTab('7');
	}
	// 地磅tab编辑
	editRow(row, val) {
		val.show();
		for (let item in this.handleRow) {
			this.handleRow[item] = row[item];
		}
		$("#rowDataForm").data('bootstrapValidator').resetForm();
	}	//添加或者编辑的数据
	cancelEdit(val) {
		val.hide();
		$("#rowDataForm").data('bootstrapValidator').resetForm();
	}
	editSubmit(val) {
		$('#rowDataForm').bootstrapValidator('validate');
		let isValid = $('#rowDataForm').data('bootstrapValidator').isValid();
		if (isValid) {
			let reqdata = '';
			for (let item in this.handleRow) {
				if (item == 'carNumber') {
					reqdata += item + '=' + this.handleRow[item];
				} else {
					reqdata += '&' + item + '=' + this.handleRow[item];
				}
			}
			this.jsonApiService.http("weighbridge/updateWeighBridge.html", reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				if (result.success) {
					this.getTableDataTab('7');
					this.cancelEdit(val);
				}
			})
		}
	}
	// 删除地磅数据
	deleteRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			var reqdata = "ids=" + row.id;
			this.jsonApiService.http('weighbridge/deleteBatch.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.getTableDataTab('7');
			})
		})
	}
	activeSelected: any;//双击高亮行
	//待维修设备,双击刷新数据绘图
	waitRepairedRowSelect(row, type) {
		this.activeSelected = row.id;
		switch (type) {
			case 'wait':
				if (!row.faultTime) {
					this.jsonApiService.message('该设备没有故障时间!');
					return;
				}
				let temStartWait = common.mmsstoTimestamp(row.faultTime);
				this.startTime = row.faultTime;
				this.endTime = common.getTimeMmss(new Date(temStartWait + 3 * 24 * 3600 * 1000));
				break;
			case 'fixed':
				let temStartFixed = common.mmsstoTimestamp(row.repairedTime);
				this.startTime = common.getTimeMmss(new Date(temStartFixed - 1 * 24 * 3600 * 1000));
				this.endTime = common.getTimeMmss(new Date(temStartFixed + 2 * 24 * 3600 * 1000));
				break;
			case 'question':
				this.startTime = row.startDate;
				this.endTime = row.endDate;
				break;
			//			case 'alert':
			//				if(!row.offTime){
			//					this.jsonApiService.message('没有警报发生时间!');
			//					return;
			//				}
			//				let temStartAlert = new Date(row.offTime);
			//				this.startTime = row.offTime;
			//				this.endTime = row.onTime?row.onTime:common.getTimeMmss(new Date(temStartAlert.setDate(temStartAlert.getDate() + 3)));
			//				break;
			default:
				break;
		}
		$('#datetimepicker1').val(this.startTime);
		$('#datetimepicker2').val(this.endTime);
		this.showCheart();
	}
	// 标记设备状态打开的弹框的一些参数

	sensorSelectAll: any = {
		faultTypeName: '传感器问题',
		programType: '202',
		text: '传感器问题',
		selected: false,
	}
	GPSSelectAll: any = {
		faultTypeName: 'GPS问题',
		programType: '203',
		text: 'GPS问题',
		selected: false,
	}
	// 传感器的渲染数组
	sensorModuleList: any = [];
	GPSProblemList = {
		startTime: '',
		endTime: '',
		operator: '',
		operatingTime: '',
		gpsProblem: '',
		selected: false,
	};
	GPSModuleList: any = [{
		faultTypeName: 'GPS问题',
		programType: '203',
		text: '无GPS',
		code: 'GP1',
		selected: false
	}, {
		faultTypeName: 'GPS问题',
		programType: '203',
		text: '停车速度平直',
		code: 'GP2',
		selected: false
	}, {
		faultTypeName: 'GPS问题',
		programType: '203',
		text: '大段丢失',
		code: 'GP3',
		selected: false
	}, {
		faultTypeName: 'GPS问题',
		programType: '203',
		text: '偶尔丢失',
		code: 'GP4',
		selected: false
	}]
	// 初始化传感器和gps问题
	initSeneorGps() {
		this.jsonApiService.http_obj("system/getDeviceBaseInfoByDeviceId.html", { deviceId: this.deviceId }).subscribe(result => {
			// 新增显示续费的信息 2020-10-12 张卓
			if (result.data.projectCarInfo) {
				this.renewalInfo = JSON.parse(JSON.stringify(result.data.projectCarInfo))
				// 过期判断
				if (this.renewalInfo.renewalDueTime) {
					let date = new Date();
					let now = date.getTime()
					let overlineDate = new Date(this.renewalInfo.renewalDueTime).getTime()
					if (overlineDate > now) {
						this.renewalInfo.isOverDate = "未到期";
					} else {
						this.renewalInfo.isOverDate = "已到期";
					}
				}
			} else {
				this.renewalInfo = ''
			}
			//编辑设备信息 回显标记设备状态的标记 gps问题和编辑表单
			this.getEditDeviceInfo();
			this.haveRepaireObj = result.data.haveRepaired;
			// 添加设备状态中的传感器的数据
			if (result.data.sensorChannel && result.data.sensorChannel.length > 0) {
				let temArr: any = [];
				for (var j = 0; j < result.data.sensorChannel.length; j++) {
					let obj = {
						value: result.data.sensorChannel[j],
						flag: false,
						isFront: '0'
					}
					if (result.data.coef) {
						if (result.data.coef[+result.data.sensorChannel[j] - 1]) {
							obj.flag = true;
						}
					}
					if (result.data.sensorAxle && result.data.sensorAxle.length > 0) {
						obj.isFront = result.data.sensorAxle[j]
					}
					//					if(result.data.sensorAxle.length == result.data.sensorChannel.length){
					//						obj.isFront= result.data.sensorAxle[j]
					//					}
					temArr.push(obj);
				}
				result.data.sensorChannel = temArr;
				this.loadSensorModule(result.data.sensorChannel);

			} else {
				this.loadSensorModule([]);
			}
			this.deviceOffline.selected = false;
			this.deviceRepairedIspush.selected = false;
		})
	}
	//加载传感器数据
	loadSensorModule(data) {
		this.sensorModuleList = [];
		for (let item of data) {
			let obj = {
				flag: item.flag,
				value: item.value,
				text: '传感器' + item.value,
				faultTypeName: '传感器问题',
				programType: '202',
				startTime: '',
				endTime: '',
				operator: '',
				operatingTime: '',
				sensorProblem: '',
				selected: false,
				isFront: item.isFront,
				child: [{
					text: '正负52万',
					code: 'SP1',
					selected: false,
				}, {
					text: '偶尔52万',
					code: 'SP1-1',
					selected: false,
				}, {
					text: '经常52万',
					code: 'SP1-2',
					selected: false,
				}, {
					text: '乱跳',
					code: 'SP2',
					selected: false,
				}, {
					text: '形变小',
					code: 'SP3',
					selected: false,
				}, {
					text: '方向反',
					code: 'SP4',
					selected: false,
				}, {
					text: '平直',
					code: 'SP5',
					selected: false,
				}]
			}
			this.sensorModuleList.push(obj);
		}
	}
	// 标记设备状态打开的弹框
	sensorSelectAllClick() {
		this.sensorSelectAll.selected = !this.sensorSelectAll.selected;
	}
	// 
	vIconQ: string = '0';
	isShowQuestion: boolean = true;
	// 点击标记设备状态按钮
	deviceStatusChange() {
		if (!this.deviceStatus) {
			$('#chart').width("62%")
			$('#deviceStatusModuleBox').css('display', 'block');
			$(window).trigger('resize');
			this.deviceStatus = true;
		} else {
			$('#chart').width("100%")
			//			$('#chart').children("div").width("100%")
			//			$('#chart').children("div").children("canvas").width("100%")
			$('#deviceStatusModuleBox').css('display', 'none');
			$(window).trigger('resize');
			this.deviceStatus = false;
		}
	}
	// 传感器选择的
	sensorLisSelected(id, code) {
		for (let item of this.sensorModuleList) {
			if (item.value == id) {
				for (let lis of item.child) {
					if (lis.code == code) {
						lis.selected = !lis.selected;
					} else {
						lis.selected = false;
					}
				}
			}
		}
		this.sensorSelectAll.selected = false;
		for (let item of this.sensorModuleList) {
			for (let lis of item.child) {
				if (lis.selected) {
					this.sensorSelectAll.selected = true;
					break;
				}
			}
		}
	}
	// GPS全选框
	GPSSelectAllClick() {
		this.GPSSelectAll.selected = !this.GPSSelectAll.selected;
	}
	// GPS列表选择
	GPSLisSelected(code) {
		for (let lis of this.GPSModuleList) {
			if (lis.code == code) {
				lis.selected = !lis.selected;
				lis.selected ? this.GPSSelectAll.selected = true : this.GPSSelectAll.selected = false;
			} else {
				lis.selected = false;
			}

		}
	}
	//更新设备状态
	updataDeviceStatus() {
		let sensorProblem: string = '', gpsProblem: string = '', sensorFlag: any, gpsFlag: any;
		for (let item of this.sensorModuleList) {
			for (let lis of item.child) {
				if (lis.selected) {
					if (sensorProblem) {
						sensorProblem += ',' + item.text + '-' + lis.text;
					} else {
						sensorProblem += item.text + '-' + lis.text;
					}
				}
			}
		}
		for (let item of this.GPSModuleList) {
			if (item.selected) {
				gpsProblem = item.text;
			}
		}
		if (this.sensorSelectAll.selected) {
			sensorFlag = 1;
		} else {
			sensorFlag = 0;
		}
		if (this.GPSSelectAll.selected) {
			gpsFlag = 1;
		} else {
			gpsFlag = 0;
		}
		if (!this.deviceId) {
			this.jsonApiService.message('请选择设备');
			return;
		}
		if (!sensorFlag && !gpsFlag) {
			this.jsonApiService.message('请选择问题分类');
			return;
		}
		this.jsonApiService.confirm_message('您确定要更新设备状态？').then(() => {
			let reqdata = {
				sensor: sensorFlag,
				gps: gpsFlag,
				deviceId: this.deviceId,
				sensorProblem: sensorProblem,
				gpsProblem: gpsProblem,
				startDate: $('#datetimepicker3').val(),
				endDate: $('#datetimepicker4').val(),
			};
			this.jsonApiService.http_obj("car/updateCarStatus.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.getEditDeviceInfo();
				}
			})
		})
	}
	page: any = {
		id: '',
		companyId: '',
		carNumber: '',
		deviceId: '',
		useTypeL1: '',
		useTypeL2: '',
		sensorType: '2',
		sensorAmount: '',
		sensorChannel: [],
		carAxleAmount: '',
		gpsAntenna: '',
		gsmAntenna: '',
		phone: '',
		driverName: '',
		sensorAxle: [], //传感器通道
		sensorPosition: [], //安装位置
	};
	deviceSensorArr: any = [{
		id: 1,
		text: '通道1',
		checked: false
	}, {
		id: 2,
		text: '通道2',
		checked: false
	}, {
		id: 3,
		text: '通道3',
		checked: false
	}, {
		id: 4,
		text: '通道4',
		checked: false
	}, {
		id: 5,
		text: '通道5',
		checked: false
	}, {
		id: 6,
		text: '通道6',
		checked: false
	}, {
		id: 7,
		text: '通道7',
		checked: false
	}, {
		id: 8,
		text: '通道8',
		checked: false
	}, {
		id: 9,
		text: '通道9',
		checked: false
	}, {
		id: 10,
		text: '通道10',
		checked: false
	}, {
		id: 11,
		text: '通道11',
		checked: false
	}, {
		id: 12,
		text: '通道12',
		checked: false
	}, {
		id: 13,
		text: '通道13',
		checked: false
	}, {
		id: 14,
		text: '通道14',
		checked: false
	}, {
		id: 15,
		text: '通道15',
		checked: false
	}, {
		id: 16,
		text: '通道16',
		checked: false
	}]
	// 编辑页面的数据
	carTypeList = carTypeListObj.carTypeList
	// 打开编辑窗口
	editDeviceInfo(modal) {
		if (!this.deviceId) {
			this.jsonApiService.message('请选择设备');
			return;
		}
		modal.show();
		this.getEditDeviceInfo();
	}
	//传感器类型change回调
	sensorTypeChange(val) {
		this.page.sensorType = val;
	}
	//请求传感器类型的接口
	querySensor() {
		this.jsonApiService.http('sensorManage/querySensorList.html', '').subscribe(data => {
			if (data.success) {
				this.inputParam = data.data
			}
		})
	}
	inputParam: any = [];
	sensorSelected(data) {
		this.page.sensorType = data.sensorType
	}
	//gps天线change回调
	gpsAntennaChange(val) {
		this.page.gpsAntenna = val;
		// if (this.page.gsmAntenna != val) {
		// 	this.gsmAntennaChange(val);
		// }
		for (var i = 0; i < allSelectOptionsObj.gsmOptions.length; i++) {
			if (allSelectOptionsObj.gsmOptions[i].text == val) {
				this.page.gsmAntenna = val;
			}
		}
	}
	//gsm天线change回调
	gsmAntennaChange(val) {
		this.page.gsmAntenna = val;
		// if (this.page.gpsAntenna != val) {
		// 	this.gpsAntennaChange(val);
		// }
		for (var i = 0; i < allSelectOptionsObj.gpsOptions.length; i++) {
			if (allSelectOptionsObj.gpsOptions[i].text == val) {
				this.page.gpsAntenna = val;
			}
		}
	}
	//全局请求 天线配置接口 GPS天线/GSM天线
	getGpsInfo() {
		this.jsonApiService.http("gpsAntenna/getGpsInfo.html", '').subscribe(data => {
			if (data.success) {
				var obj;
				allSelectOptionsObj.gpsOptions = [];
				allSelectOptionsObj.gsmOptions = [];
				for (var i = 0; i < data.data.length; i++) {
					if (data.data[i].type == 'GPS天线') {
						obj = {
							value: data.data[i].antennaName,
							text: data.data[i].antennaName
						}
						allSelectOptionsObj.gpsOptions.push(obj);

					} else if (data.data[i].type == 'GSM天线') {
						obj = {
							value: data.data[i].antennaName,
							text: data.data[i].antennaName
						}
						allSelectOptionsObj.gsmOptions.push(obj);
					}
				}
				this.gpsOptions = allSelectOptionsObj.gpsOptions;
				this.gsmOptions = allSelectOptionsObj.gsmOptions;
			}
		})
	}
	// 传感器选择框
	deviceSensorChange(id, e) {
		// this.page.sensorChannel = [];
		// if(e.target.checked){
		// 	this.deviceSensorArr[id-1].checked = true;
		// }else{
		// 	this.deviceSensorArr[id-1].checked = false;
		// }
		// for(let item of this.deviceSensorArr){
		// 	if(item.checked){
		// 		this.page.sensorChannel.push(item.id);
		// 	}
		// }
		// this.page.sensorAmount = this.page.sensorChannel.length||'';


		var sensorAxleList = [];
		this.page.sensorChannel = [];
		let sensor;
		var listFront = JSON.parse(JSON.stringify(this.sensorAxleFront));
		var listAfter = JSON.parse(JSON.stringify(this.sensorAxleAfter));
		var listChannel = JSON.parse(JSON.stringify(this.checkChannel));
		var that = this;

		if (e.target.checked) {
			that.deviceSensorArr[id - 1].checked = true;
			sensor = {
				mark: id,
				text: id,
				checked: false,
				isDisable: false
			}
			listFront.push(sensor);
			listAfter.push(sensor);
			listChannel.push(sensor);
			that.sensorAxleFront = that.deepClone(listFront);
			that.sensorAxleAfter = that.deepClone(listAfter);
			that.checkChannel = that.deepClone(listChannel);
			// that.sensorAxleAfter = that.deepClone(that.sensorAxleFront);
			// that.checkChannel = that.deepClone(that.sensorAxleFront);

			that.sensorAxleFront.sort(that.compare('mark'));
			that.sensorAxleAfter.sort(that.compare('mark'));
			that.checkChannel.sort(that.compare('mark'));
		} else {
			that.deviceSensorArr[id - 1].checked = false;
			if (that.sensorAxleFront.length != 0) {
				for (let i = 0; i < that.sensorAxleFront.length; i++) {
					if (that.sensorAxleFront[i].mark == id) {
						listFront.splice(i, 1);
						listAfter.splice(i, 1);
						listChannel.splice(i, 1);
						this.clear(id)
						that.sensorAxleFront = that.deepClone(listFront);
						that.sensorAxleAfter = that.deepClone(listAfter);
						that.checkChannel = that.deepClone(listChannel);

						// that.sensorAxleAfter = that.deepClone(that.sensorAxleFront);
						// that.checkChannel = that.deepClone(that.sensorAxleFront);

					}
				}
			}
		}
		for (let item of this.deviceSensorArr) {
			if (item.checked) {
				this.page.sensorChannel.push(item.id);
			}
		}
		this.page.sensorAmount = this.page.sensorChannel.length || '';

		for (let j = 0; j < this.sensorAxleAfter.length; j++) {
			if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(0)
			} else if (this.sensorAxleAfter[j].checked) {
				sensorAxleList.push(2)
			} else if (this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(1)
			}
		}
		this.page.sensorAxle = this.deepClone(sensorAxleList);

		this.showCheck(that.checkChannel)
	}
	// 关闭编辑窗口
	closeEditDeciceModal(modal) {
		modal.hide();
	}
	// 编辑设备信息 
	getEditDeviceInfo() {
		this.clearEditDeviceInfo();
		this.jsonApiService.http_obj("car/getCarInfoByDeviceId.html", { deviceId: this.deviceId }).subscribe(data => {
			if (data.success) {
				let result = data.data;
				for (let item in this.page) {
					if (item == 'sensorChannel' && !result[item]) {
						result[item] = [];
					}
					this.page[item] = result[item];
				}
				let resultChannel = [];
				if (result.sensorChannel) {
					for (let item of result.sensorChannel) {
						if (item && item !== 'null') {
							resultChannel.push(item);
						}
					}
					result.sensorChannel = resultChannel;
				}
				for (let item of this.deviceSensorArr) {
					item.checked = false;
				}
				if (result.sensorChannel.length > 0) {
					for (var i = 0; i < result.sensorChannel.length; i++) {
						this.deviceSensorArr[result.sensorChannel[i] - 1].checked = true;
					}
				}
				if (result.sensorProblemList) {
					if (result.sensorProblemList.length > 0) {
						//                      this.sensorSelectAll.selected = true;
						for (let sensor of result.sensorProblemList) {
							let sensorItem = sensor.sensorProblem.split('-');
							for (let item of this.sensorModuleList) {
								if (item.text == sensorItem[0]) {
									item.startTime = sensor.startTime;
									item.endTime = sensor.endTime;
									item.operator = sensor.operator;
									item.operatingTime = sensor.operatingTime;
									item.sensorProblem = sensor.sensorProblem;
									for (let lis of item.child) {
										if (lis.text == sensorItem[1]) {
											lis.selected = true;
											item.selected = true;
										} else {
											lis.selected = false;
										}
									}
								}
							}
						}
					}
				}
				if (result.gpsProblemEntity) {
					let gps = result.gpsProblemEntity;
					this.GPSProblemList.startTime = gps.startTime;
					this.GPSProblemList.endTime = gps.endTime;
					this.GPSProblemList.operator = gps.operator;
					this.GPSProblemList.operatingTime = gps.operatingTime;
					this.GPSProblemList.gpsProblem = gps.gpsProblem;
					for (let item of this.GPSModuleList) {
						if (item.text == gps.gpsProblem) {
							item.selected = true;
							this.GPSProblemList.selected = true;
						} else {
							item.selected = false;
						}
					}
				}
				$('#useTypeSelect').val(this.page.useTypeL2).trigger('change');

				this.ChannelLen = data.data.carAxleAmount;
				//选中通道值
				this.showLocation(data.data.sensorChannel, data.data.sensorPosition, data.data.carAxleAmount)

				let sensor1, sensor2;
				this.sensorAxleFront = []; this.sensorAxleAfter = [];
				var AxleFrontList = JSON.parse(JSON.stringify(this.sensorAxleFront))
				var AxleAfterList = JSON.parse(JSON.stringify(this.sensorAxleAfter))
				// this.sensorAxleAfter = this.deepClone(this.sensorAxleFront); //深拷贝

				for (let j = 0; j < data.data.sensorChannel.length; j++) {
					if (data.data.sensorAxle == null || data.data.sensorAxle.length == 0) {
						sensor1 = {
							mark: data.data.sensorChannel[j],
							text: data.data.sensorChannel[j],
							checked: false,
							isDisable: false
						}

						AxleFrontList.push(sensor1);
						AxleAfterList.push(sensor1);

					} else {
						for (let k = 0; k < data.data.sensorAxle.length; k++) {
							if (data.data.sensorAxle[k] == 0 && k == j) {
								sensor1 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: false,
									isDisable: false
								}
								AxleFrontList.push(sensor1);
								AxleAfterList.push(sensor1);

							} else if (data.data.sensorAxle[k] == 1 && k == j) {
								sensor1 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: true,
									isDisable: false
								}
								sensor2 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: false,
									isDisable: true
								}
								AxleFrontList.push(sensor1);
								AxleAfterList.push(sensor2);
							} else if (data.data.sensorAxle[k] == 2 && k == j) {
								sensor1 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: false,
									isDisable: true
								}
								sensor2 = {
									mark: data.data.sensorChannel[j],
									text: data.data.sensorChannel[j],
									checked: true,
									isDisable: false
								}
								AxleFrontList.push(sensor1);
								AxleAfterList.push(sensor2);
							}
						}
					}
					this.sensorAxleFront = this.deepClone(AxleFrontList); //深拷贝
					this.sensorAxleAfter = this.deepClone(AxleAfterList); //深拷贝
				}
			} else {
				this.jsonApiService.message(data.message);
			}
		})

		//算法问题清空
		for (let lis of this.algorithmQuestionList) {
			lis.selected = false;
		}

	}
	// 清空编辑设备信息表
	clearEditDeviceInfo() {
		this.GPSSelectAll.selected = false;
		this.sensorSelectAll.selected = false;
		for (let item in this.page) {
			this.page[item] = '';
			if (item == 'sensorChannel') {
				this.page[item] = [];
			}
		}
		for (let item of this.GPSModuleList) {
			item.selected = false;
		}
		for (let item of this.sensorModuleList) {
			item.startTime = '';
			item.endTime = '';
			item.operator = '';
			item.operatingTime = '';
			item.sensorProblem = '';
			for (let lis of item.child) {
				lis.selected = false;
			}
		}
		for (let item of this.deviceSensorArr) {
			item.checked = false;
		}
		this.GPSProblemList = {
			startTime: '',
			endTime: '',
			operator: '',
			operatingTime: '',
			gpsProblem: '',
			selected: false,
		};
		// 重置表单的数据	
		$("#sensorAmount").val("")
		$('#useTypeSelect').val(null).trigger("change");
	}
	// 提交表单数据
	submitEditDeciceModal(modal) {
		var reqdata = new FormData();
		this.page.useTypeL2 = $('#useTypeSelect').val();
		this.page.useTypeL1 = $('#useTypeSelect').val().slice(0, 2);
		if (this.page.sensorChannel) {
			for (let iems of this.page.sensorChannel) {
				if (!iems) iems = '';
			}
		} else {
			this.page.sensorChannel = [];
		}
		if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
			if (this.sensorAxleAfter.length != 0) {
				let sensorAxleList = [];
				for (let j = 0; j < this.sensorAxleAfter.length; j++) {
					sensorAxleList.push(0)
				}
				this.page.sensorAxle = this.deepClone(sensorAxleList);
			}
		}
		// if(!$('#sensorAmount').val()){
		// 	this.page.sensorAmount = ""
		// }

		for (let item in this.page) {
			if (item == 'sensorPosition') {
				this.page.sensorPosition = this.filterPosition(this.installArray);
				reqdata.append('sensorPositionJson', JSON.stringify(this.page.sensorPosition));
			} else {
				reqdata.append(item, common.stringTrim(this.page[item]));
			}
		}
		this.jsonApiService.form_http("car/edit.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.getEditDeviceInfo();
				this.initSeneorGps();
				// this.initOrderDeviceModal(this.activeSelected)
				modal.hide();
			}
		})
	}
	// 增加离线和限制进厂选择框
	deviceOffline: any = {
		faultTypeName: '主机问题',
		programType: '201',
		text: '离线',
		selected: false
	}
	deviceRepairedIspush: any = {
		text: '限制进厂',
		selected: false
	}
	deviceOfflineClick() {
		this.deviceOffline.selected = !this.deviceOffline.selected;
	}
	deviceRepairedIspushClick() {
		this.deviceRepairedIspush.selected = !this.deviceRepairedIspush.selected;
	}
	//添加设备维修
	addDeviceRepaired() {
		let data: any = [];
		let sensorProblem: string = '', gpsProblem: string = '', sensorFlag: any, gpsFlag: any;
		if (this.sensorSelectAll.selected) {
			sensorFlag = 1;
			for (let item of this.sensorModuleList) {
				for (let lis of item.child) {
					if (lis.selected) {
						if (sensorProblem) {
							sensorProblem += ',' + item.text + '-' + lis.text;
						} else {
							sensorProblem += item.text + '-' + lis.text;
						}
					}
				}
			}
		} else {
			sensorFlag = 0;
		}
		if (this.GPSSelectAll.selected) {
			gpsFlag = 1;
			for (let item of this.GPSModuleList) {
				if (item.selected) {
					gpsProblem = item.text;
				}
			}
		} else {
			gpsFlag = 0;
		}
		if (sensorProblem) {
			let sensorObj = {
				programType: '202',
				deviceId: this.deviceId,
				carNumber: this.carNumber,
				faultTypeName: '传感器问题',
				faultTime: this.startProblemTime,
				faultPhenomenon: sensorProblem.split(','),
				isPush: this.deviceRepairedIspush.selected ? '1' : '',
			}
			data.push(sensorObj);
		}
		if (gpsProblem) {
			let gpsObj = {
				programType: '203',
				deviceId: this.deviceId,
				carNumber: this.carNumber,
				faultTypeName: 'GPS问题',
				faultTime: this.startProblemTime,
				faultPhenomenon: gpsProblem.split(','),
				isPush: this.deviceRepairedIspush.selected ? '1' : '',
			}
			data.push(gpsObj);
		}
		if (this.deviceOffline.selected) {
			let offlineObj = {
				programType: this.deviceOffline.programType,
				deviceId: this.deviceId,
				carNumber: this.carNumber,
				faultTypeName: '主机问题',
				faultTime: this.startProblemTime,
				faultPhenomenon: this.deviceOffline.text.split(','),
				isPush: this.deviceRepairedIspush.selected ? '1' : '',
			}
			data.push(offlineObj);
		}
		if (!sensorProblem && !gpsProblem && !this.deviceOffline.selected) {
			this.jsonApiService.message('请选择故障类型');
			return;
		}
		let reqdata = 'list=' + JSON.stringify(data) + '&sensor=' + sensorFlag + '&gps=' + gpsFlag;
		// 限制车辆的“开始时间” 要小于“ 维修时间”，做个弹框，提示内容：“ 粤B33322 于[xxxx-xx-xx xx:xx:xx]已维修，请与[xxx]（维修人） 核实维修情况 ”，是，继续录入维修，否，取消该次操作
		let selectTime = new Date($('#datetimepicker3').val()).getTime();
		let lastServiceTime = this.haveRepaireObj ? this.haveRepaireObj.repairedTime : null
		let lastTime = new Date(lastServiceTime).getTime();
		// 点击了限制进厂 并且 选择的时间小于最后一次维修的时间 就进行提示
		if (this.deviceRepairedIspush.selected && (selectTime < lastTime)) {
			let carNumber = this.haveRepaireObj.carNumber;
			let repairedUser = this.haveRepaireObj.repairedUserName;
			// 提示
			this.notificationService.smartMessageBox({
				title: "提示",
				content: carNumber + '于 [' + lastServiceTime + '] 已维修，请与 [' + repairedUser + ']（维修人）核实维修情况',
				buttons: '[继续录入][取消]'
			}, (ButtonPressed) => {
				if (ButtonPressed === "继续录入") {
					// 继续录入就直接录入
					this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
						this.jsonApiService.message(data.message);
					})
				}
				if (ButtonPressed === "取消") {
					// this.notificationService.smallBox({
					// 	content: "操作取消",
					// 	timeout: 3000
					// });
					return;
				}
			});
		} else {
			this.jsonApiService.http('deviceRepaired/validateRecord.html', 'deviceId=' + this.deviceId).subscribe(result => {
				if (result.valid) {
					this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
						this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
							this.jsonApiService.message(data.message);
						})
					})
				} else {
					this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
						this.jsonApiService.message(data.message);
					})
				}
			})
		}
		// this.jsonApiService.http('deviceRepaired/validateRecord.html', 'deviceId=' + this.deviceId).subscribe(result => {
		// 	if(result.valid) {
		// 		this.jsonApiService.confirm_message(result.message + '确认要继续提交?').then(() => {
		// 			this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
		// 				this.jsonApiService.message(data.message);
		// 			})
		// 		})
		// 	} else {
		// 		this.jsonApiService.http("deviceRepaired/insertDeviceRepairedBatch.html", reqdata).subscribe(data => {
		// 			this.jsonApiService.message(data.message);
		// 		})
		// 	}
		// })
	}
	// 提交传感器问题,单个传感器
	updateSensorProblem(item) {
		let sensorProblem: string = '';
		for (let lis of item.child) {
			if (lis.selected) {
				sensorProblem = item.text + '-' + lis.text;
			}
		}
		if (!sensorProblem) {
			this.jsonApiService.message('请选择传感器问题')
			return;
		}
		let reqdata = {
			deviceId: this.deviceId,
			index: item.value - 1,
			startTime: $('#datetimepicker3').val(),
			endTime: $('#datetimepicker4').val(),
			sensorProblem: sensorProblem
		}
		this.jsonApiService.http_obj("car/updateSensorProblem.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.getEditDeviceInfo();
			}
		})
	}
	// 提交GPS问题,单个GPS
	updateGPSProblem() {
		let gpsProblem: string = '';
		for (let item of this.GPSModuleList) {
			if (item.selected) {
				gpsProblem = item.text;
			}
		}
		if (!gpsProblem) {
			this.jsonApiService.message('请选择GPS问题');
			return;
		}
		let reqdata = {
			deviceId: this.deviceId,
			startTime: $('#datetimepicker3').val(),
			endTime: $('#datetimepicker4').val(),
			gpsProblem: gpsProblem
		}
		this.jsonApiService.http_obj("car/updateGpsProblem.html", reqdata).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				this.getEditDeviceInfo();
			}
		})
	}
	// 问题区间数据查看,查看问题区间重量曲线图
	dataDrawEchartBMap(item) {
		let queryParams = {
			deviceId: this.deviceId,
			carNumber: this.carNumber,
			startDate: item.startTime,
			endDate: item.endTime,
		}
		let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
		common.setCookie('jumpFromOrderManagenment', JSON.stringify(queryParams));
		window.open(BaseURL + '#/system-config/data-optimization');
		//      $('#echartMapModal').show();
		//      this.echartParam = {
		//          deviceId: this.deviceId,
		//          carNumber: this.carNumber,
		//          startTime: item.startTime,
		//          endTime: item.endTime,
		//          coefficient: this.deviceBaseInfo.coef
		//      }
	}
	closeEchartMapModal() {
		$('#echartMapModal').hide();
	}

	/**
	 *  曲线图查看
	 */
	drawTrackList: any;
	echartParam: any;
	isShowMapView: boolean = false;//默认不显示地图轨迹
	//获取到绘制轨迹数据,传递给地图组件
	initMapDate(value) {
		this.drawTrackList = value;
	}
	// 是否显示地图
	isHasMapView(val) {
		this.isShowMapView = val;
	}














	/* 传感器通道 前轴 后轴  通道 */

	//通道 前
	sensorAxleFrontChange(item, e) {
		let sensorAxleList = [];
		for (let i = 0; i < this.sensorAxleFront.length; i++) {
			if (item.mark == this.sensorAxleFront[i].mark) {
				if (e.target.className.indexOf('wayCheck') != -1) {

					this.sensorAxleFront[i].checked = false;
					this.sensorAxleAfter[i].isDisable = false
				} else {
					this.sensorAxleFront[i].checked = true;
					this.sensorAxleAfter[i].isDisable = true
				}
			}
		}

		for (let j = 0; j < this.sensorAxleAfter.length; j++) {
			if (!this.sensorAxleAfter[j].checked && !this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(0)
			} else if (this.sensorAxleAfter[j].checked) {
				sensorAxleList.push(2)
			} else if (this.sensorAxleAfter[j].isDisable) {
				sensorAxleList.push(1)
			}
		}
		this.page.sensorAxle = this.deepClone(sensorAxleList);
	}
	//深拷贝浅拷贝
	deepClone(obj) {
		let objClone = Array.isArray(obj) ? [] : {};
		if (obj && typeof obj === "object") {
			for (let key in obj) {
				if (obj.hasOwnProperty(key)) {
					//判断ojb子元素是否为对象，如果是，递归复制
					if (obj[key] && typeof obj[key] === "object") {
						objClone[key] = this.deepClone(obj[key]);
					} else {
						//如果不是，简单复制
						objClone[key] = obj[key];
					}
				}
			}
		}
		return objClone;
	}
	//通道 后
	sensorAxleAfterChange(item, e) {
		let sensorAxleList = [];
		for (let i = 0; i < this.sensorAxleAfter.length; i++) {
			if (item.mark == this.sensorAxleAfter[i].mark) {
				if (e.target.className.indexOf('wayCheck') != -1) {

					this.sensorAxleAfter[i].checked = false;
					this.sensorAxleFront[i].isDisable = false
				} else {
					this.sensorAxleAfter[i].checked = true;
					this.sensorAxleFront[i].isDisable = true
				}
			}
		}

		for (let j = 0; j < this.sensorAxleFront.length; j++) {
			if (!this.sensorAxleFront[j].checked && !this.sensorAxleFront[j].isDisable) {
				sensorAxleList.push(0)
			} else if (this.sensorAxleFront[j].checked) {
				sensorAxleList.push(1)
			} else if (this.sensorAxleFront[j].isDisable) {
				sensorAxleList.push(2)
			}
		}
		this.page.sensorAxle = this.deepClone(sensorAxleList)
	}
	//过滤通道数据
	filterPosition(value) {
		var List = [];
		var ListParant = [];
		this.page.sensorPosition = [];
		for (let j = 0; j < value.length; j++) {
			if (value[j].positionLMR[0].sensorChannel.length != 0
				&& value[j].positionLMR[1].sensorChannel.length != 0
				&& value[j].positionLMR[2].sensorChannel.length != 0) {
				List.push(value[j])
			} else {

				for (let a = 0; a < value[j].positionLMR.length; a++) {

					if (value[j].positionLMR[a].sensorChannel.length != 0) {
						ListParant.push(value[j].positionLMR[a]);
					}
				}
				if (ListParant.length != 0) {
					var positionLMR = {
						"index": j + 1,
						"positionLMR": ListParant
					}
					List.push(positionLMR);
				}

				// if(ListParant.length != 0){List.push(ListParant);}
				ListParant = [];
				continue;
			}
		}
		return List;
	}
	//显示安装位置
	showLocation(sensorChannel, value, Lens) {
		var installArray = [
			{
				"index": 1,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 2,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 3,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 4,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 5,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
			{
				"index": 6,
				"positionLMR": [
					{
						"position": "L",
						"sensorChannel": []
					},
					{
						"position": "M",
						"sensorChannel": []
					},
					{
						"position": "R",
						"sensorChannel": []
					}
				]
			},
		] //安装位置
		let sensor;
		let array = [];
		this.checkChannel = [];
		if (sensorChannel != 0) {
			for (let i = 0; i < sensorChannel.length; i++) {
				sensor = {
					mark: sensorChannel[i],
					text: sensorChannel[i],
					checked: false,
					isDisable: false
				}
				this.checkChannel.push(sensor);
				this.checkChannel.sort(this.compare('mark'));
				var checkChannelList = JSON.parse(JSON.stringify(this.checkChannel));
			}
		}
		var len
		if (value != null && value.length != 0) {
			len = value[value.length - 1].index
		} else {
			if (Lens == "") { Lens = 0 }
			len = Lens;
		};
		if (value != 0 && value != null) {
			for (let j = 0; j < installArray.length; j++) {
				for (let k = 0; k < value.length; k++) {
					if (installArray[j].index == value[k].index) {
						for (let f = 0; f < value[k].positionLMR.length; f++) {
							if (value[k].positionLMR[f].position == 'L') {
								installArray[j].positionLMR[0].sensorChannel = value[k].positionLMR[f].sensorChannel;
								continue;
							}
							if (value[k].positionLMR[f].position == 'M') {
								installArray[j].positionLMR[1].sensorChannel = value[k].positionLMR[f].sensorChannel;
								continue;
							}
							if (value[k].positionLMR[f].position == 'R') {
								installArray[j].positionLMR[2].sensorChannel = value[k].positionLMR[f].sensorChannel;
								continue;
							}
						}
						break;
					}
				}

			}
			if (len > Lens || len == Lens) {
				if (len != 0) { installArray.splice(len, 6 - len); }
			} else {
				if (len != 0) { installArray.splice(Lens, 6 - Lens); }
			}

			this.installArray = this.deepClone(installArray)
		} else {
			if (len != 0) { installArray.splice(len, 6 - len); }
			this.installArray = this.deepClone(installArray)
		}

		this.showCheck(this.checkChannel);
	}
	compare(property) {
		return function (a, b) {
			var value1 = a[property];
			var value2 = b[property];
			return value1 - value2;
		}
	}
	showCheck(value) {
		var showCheckList = [];
		for (var a = 0; a < this.installArray.length; a++) {
			for (var b = 0; b < this.installArray[a].positionLMR.length; b++) {
				for (var c = 0; c < this.installArray[a].positionLMR[b].sensorChannel.length; c++) {
					showCheckList.push(this.installArray[a].positionLMR[b].sensorChannel[c])
				}
			}
		}

		for (var i = 0; i < value.length; i++) {
			for (var j = 0; j < showCheckList.length; j++) {
				if (value[i].mark == showCheckList[j]) {
					value[i].isDisable = true;
					break;
				}
			}
		}

		this.checkChannel = this.deepClone(value);
	}
	clear(value) {
		for (let j = 0; j < this.installArray.length; j++) {
			var sensorChannelL = this.installArray[j].positionLMR[0].sensorChannel;
			var sensorChannelM = this.installArray[j].positionLMR[1].sensorChannel;
			var sensorChannelR = this.installArray[j].positionLMR[2].sensorChannel;
			for (var k = 0; k < sensorChannelL.length; k++) {
				if (sensorChannelL[k] == value) {
					sensorChannelL.splice(k, 1);
				}
				this.installArray[j].positionLMR[0].sensorChannel = this.deepClone(sensorChannelL);
				this.installArray[j].positionLMR[0].sensorChannel.sort(this.sortNumber);
			}
			for (var h = 0; h < sensorChannelM.length; h++) {
				if (sensorChannelM[h] == value) {
					sensorChannelM.splice(h, 1);
				}
				this.installArray[j].positionLMR[1].sensorChannel = this.deepClone(sensorChannelM)
				this.installArray[j].positionLMR[1].sensorChannel.sort(this.sortNumber);;
			}
			for (var f = 0; f < sensorChannelR.length; f++) {
				if (sensorChannelR[f] == value) {
					sensorChannelR.splice(f, 1);
				}
				this.installArray[j].positionLMR[2].sensorChannel = this.deepClone(sensorChannelR);
				this.installArray[j].positionLMR[2].sensorChannel.sort(this.sortNumber);
			}
		}

		this.page.sensorPosition = this.deepClone(this.installArray)
	}
	//排序
	sortNumber(a, b) {//升序
		return a - b
	}
	//车轴数量出现安装位置
	carAxleAmountChange(value) {
		if (this.page.sensorAxle == null || this.page.sensorAxle.length == 0) {
			this.page.sensorAxle = [];
			if (this.page.sensorChannel.length != 0) {
				for (var j = 0; j < this.page.sensorChannel.length; j++) {
					let mun = "0";
					this.page.sensorAxle.push(mun);
				}
			}
		}

		var array = [];
		if (isNaN(value) == true) {
			this.jsonApiService.message('请输入数字');
			$('#carAxleAmount').val('');
			this.page.carAxleAmount = "";
			return;
		} else if (value > 6) {
			this.jsonApiService.message('车轴数量不能大于6');
			$('#carAxleAmount').val('');
			this.page.carAxleAmount = "";
			return;
		} else {
			if (value == "0") {
				this.jsonApiService.message('车轴数量不能为0');
				$('#carAxleAmount').val('');
				this.page.carAxleAmount = "";
				return;
			} else if (value == "") {
				if (this.ChannelLen == 0 && this.page.carAxleAmount == "") {
					this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
					// this.installArray = this.page.sensorPosition
				} else {
					for (var i = 0; i < 6; i++) {
						var positionLMR = {
							"index": i + 1,
							"positionLMR": [
								{
									"position": "L",
									"sensorChannel": []
								},
								{
									"position": "M",
									"sensorChannel": []
								},
								{
									"position": "R",
									"sensorChannel": []
								}
							]
						}
						array.push(positionLMR);
					}
					this.installArray = this.deepClone(array);
					this.clearcheckChannel()
				}
			} else if (value == this.ChannelLen) {
				this.showLocation(this.page.sensorChannel, this.page.sensorPosition, value)
				// this.showLocation(this.page.sensorChannel,this.installArray)
			} else {
				for (var i = 0; i < value; i++) {
					var positionLMR = {
						"index": i + 1,
						"positionLMR": [
							{
								"position": "L",
								"sensorChannel": []
							},
							{
								"position": "M",
								"sensorChannel": []
							},
							{
								"position": "R",
								"sensorChannel": []
							}
						]
					}
					array.push(positionLMR);
				}
				this.installArray = this.deepClone(array);
				this.clearcheckChannel()
			}
		}

		// for(let i=0;i<this.checkChannel.length;i++){
		// 	this.checkChannel[i].isDisable = false;
		// }
	}
	//清除安装位置轴数选中
	clearcheckChannel() {
		for (var a = 0; a < this.checkChannel.length; a++) {
			this.checkChannel[a].isDisable = false;
		}
	}
	axisType: any = '' //打开那个方向传感器轴
	axisIndex: any = '' //打开那个传感器轴
	//添加传感器通道
	addinstall(index, type, modal) {
		this.axisType = type;
		this.axisIndex = index;
		if (this.page.sensorAmount) {
			modal.show();
		} else {
			this.jsonApiService.message('请先选择传感器');
		}

	}
	//选择弹框中的传感器通道
	choiceChannel(item, e) {
		for (let i = 0; i < this.checkChannel.length; i++) {
			if (item.mark == this.checkChannel[i].mark) {
				if (e.target.className.indexOf('check') != -1) {
					this.checkChannel[i].checked = false;
				} else {
					this.checkChannel[i].checked = true;
				}
			}
		}
	}
	//取消传感器弹框
	lgModalhide(modal) {
		this.axisType = '';
		this.axisIndex = '';
		modal.hide();
		for (let i = 0; i < this.checkChannel.length; i++) {
			if (this.checkChannel[i].checked) {
				this.checkChannel[i].checked = false;
			}
		}
		// this.checkChannel = [];
	}
	//确定传感器
	lgModalConfirm(modal) {
		let newChannel = []
		for (let i = 0; i < this.checkChannel.length; i++) {
			if (this.checkChannel[i].checked) {
				this.checkChannel[i].isDisable = true;
				if (this.axisType == 'left') {
					this.installArray[this.axisIndex - 1].positionLMR[0].sensorChannel.push(this.checkChannel[i].mark);
				} else if (this.axisType == 'middle') {
					this.installArray[this.axisIndex - 1].positionLMR[1].sensorChannel.push(this.checkChannel[i].mark);
				} else if (this.axisType == 'right') {
					this.installArray[this.axisIndex - 1].positionLMR[2].sensorChannel.push(this.checkChannel[i].mark);
				}
				// newChannel.push(this.checkChannel[i].mark)
			}
		}

		this.installArray[this.axisIndex - 1].positionLMR[0].sensorChannel.sort(this.sortNumber);
		this.installArray[this.axisIndex - 1].positionLMR[1].sensorChannel.sort(this.sortNumber);
		this.installArray[this.axisIndex - 1].positionLMR[2].sensorChannel.sort(this.sortNumber);
		this.lgModalhide(modal);
	}
	//删除选中的传感器
	cancelChannel(index, type, channel) {
		let valueList;
		if (type == 'left') {
			valueList = this.installArray[index - 1].positionLMR[0].sensorChannel;
			for (let i = 0; i < valueList.length; i++) {
				if (valueList[i] == channel) {
					valueList.splice(i, 1);
				}
			}
			this.installArray[index - 1].positionLMR[0].sensorChannel = this.deepClone(valueList)
		} else if (type == 'middle') {
			valueList = this.installArray[index - 1].positionLMR[1].sensorChannel;
			for (let j = 0; j < valueList.length; j++) {
				if (valueList[j] == channel) {
					valueList.splice(j, 1);
				}
			}
			this.installArray[index - 1].positionLMR[1].sensorChannel = this.deepClone(valueList)

		} else if (type == 'right') {
			valueList = this.installArray[index - 1].positionLMR[2].sensorChannel;
			for (let k = 0; k < valueList.length; k++) {
				if (valueList[k] == channel) {
					valueList.splice(k, 1);
				}
			}
			this.installArray[index - 1].positionLMR[2].sensorChannel = this.deepClone(valueList)
		}

		for (let l = 0; l < this.checkChannel.length; l++) {
			if (this.checkChannel[l].mark == channel) {
				this.checkChannel[l].isDisable = false;
			}
		}
	}
	// 远程清零
	resetWeightToZero() {
		if (!this.deviceId) {
			this.jsonApiService.message('设备ID不能为空');
			return;
		}
		this.jsonApiService.confirm_message('您确定要执行远程清零？').then(() => {
			let reqdata = 'protocolVersion=2&deviceId=' + this.deviceId + '&isAuto=false';
			this.jsonApiService.http("system/remotereset.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
			})
		})
	}
	//选择算法问题
	algorithmLisSelected(text) {
		for (let lis of this.algorithmQuestionList) {
			if (lis.text == text) {
				lis.selected = !lis.selected;
			} else {
				lis.selected = false;
			}
		}
	}
	//算法问题提交
	updataOrderStatus() {
		if (!this.deviceId) {
			this.jsonApiService.message('先选择车辆...');
			return;
		}
		var proType2;
		for (var i = 0; i < this.algorithmQuestionList.length; i++) {
			if (this.algorithmQuestionList[i].selected == true) {
				proType2 = this.algorithmQuestionList[i].programType
			}
		}

		if (!proType2) {
			this.jsonApiService.message('请选择问题分类');
			return;
		}

		if (!this.startTime || !this.endTime) {
			this.jsonApiService.message('开始时间和结束时间不能为空...');
			return;
		}

		this.jsonApiService.http("realtime/getRealTimeData.html", 'deviceId=' + this.deviceId).subscribe(result => {
			let params = {
				programType: proType2,
				deviceId: this.deviceId,
				version: result.data.version ? result.data.version : '',
				startDate: this.startTime,
				endDate: this.endTime,
				reason: "",
				exceptionType: "1",
				coefficient: result.data.coef ? result.data.coef : ''
			}
			let reqdata = '';
			for (let keys in params) {
				reqdata = reqdata + keys + '=' + params[keys] + '&';
			}
			reqdata = reqdata.substring(0, reqdata.length - 1);
			this.jsonApiService.http("dataExceptionRecord/addDataException.html", reqdata).subscribe(result2 => {
				this.jsonApiService.message(result2.message);
				if (result2.success) {
					// this.isDisable=false;
					//					this.load();
				}
			})
		})
	}

	isHold: boolean = true; //是否展开工具箱
	fixedRecord: any = ''; //待维修 
	isFixedRecord: boolean; //是否显示待维修
	waitFixedRecord: any = []; //最近一次维修 可能有多条
	gpsRecord: any = []; //GPS显示检测的数据
	//工具箱
	clickHold(value) {
		this.isFixedRecord = false;
		if (!this.deviceId) {
			this.jsonApiService.message("车牌号码不能为空");
			return;
		}
		if (!this.startTime || !this.endTime) {
			this.jsonApiService.message("开始时间或结束时间不能为空");
			return;
		}
		this.isHold = value;
		if (this.isHold == false) {
			this.fixedRecord = '';
			this.waitFixedRecord = [];
			let reqdata = 'deviceId=' + this.deviceId + '&startDate=' + this.startTime + '&endDate=' + this.endTime;
			this.jsonApiService.http("system/queryDeviceRepairedRecordsByDeviceId.html", reqdata).subscribe(data => {
				if (data.success) {
					this.fixedRecord = data.data.fixedRecord;
					this.waitFixedRecord = data.data.waitFixedRecord;

					if (data.data.fixedRecord) {
						this.isFixedRecord = true;
					}
				}
			})
		}
	}
	//检测GPS
	testingGPS() {
		if (!this.deviceId) {
			this.jsonApiService.message("车牌号码不能为空");
			return;
		}
		let reqdata = 'deviceId=' + this.deviceId + '&startTime=' + this.startTime + '&endTime=' + this.endTime;
		this.jsonApiService.http("stats/gpsDetection.html", reqdata).subscribe(data => {

			if (data.success) {
				if (data.data.length == 0) {
					this.jsonApiService.message("该GPS无异常");
				}
				this.gpsRecord = data.data;
			} else {
				this.jsonApiService.message(data.message);
			}
		})
	}
	//工具箱拖拽
	dragDrop() {
		//获取元素
		var dv = document.getElementById('holdAll');
		var x = 0;
		var y = 0;
		var l = 0;
		var t = 0;
		var isDown = false;
		//鼠标按下事件
		dv.onmousedown = function (e) {
			//获取x坐标和y坐标
			x = e.clientX;
			y = e.clientY;

			//获取左部和顶部的偏移量
			l = dv.offsetLeft;
			t = dv.offsetTop;
			//开关打开
			isDown = true;
			//设置样式  
			dv.style.cursor = 'move';
		}
		//鼠标移动
		window.onmousemove = function (e) {
			if (isDown == false) {
				return;
			}
			//获取x和y
			var nx = e.clientX;
			var ny = e.clientY;
			//计算移动后的左偏移量和顶部的偏移量
			var nl = nx - (x - l);
			var nt = ny - (y - t);

			dv.style.left = nl + 'px';
			dv.style.top = nt + 'px';
		}
		//鼠标抬起事件
		dv.onmouseup = function () {
			//开关关闭
			isDown = false;
			dv.style.cursor = 'default';
		}
	}
	/**
	 * 跳转服务费管理页面
	 */
	goRenewal() {
		let BaseURL = window.location.protocol + '//' + window.location.hostname + ':' + window.location.port;
		window.open(BaseURL + '#/system/renewal-manage');
	}

	// 增加的初始化公司和车辆的方法
	initCompanyAndCar(row) {

		$('#companyTree').find('.tree_company_input').val(row.companyName).change();

		$('#carNumberSelect2').val(row.deviceId).trigger('change');
		var str = $("<span class='select2-selection__rendered'>" + row.carNumber + "</span>");
		$('#carNumberSelect2').val("");
		$("#select2-carNumberSelect2-container").empty();
		$("#select2-carNumberSelect2-container").attr("title", "");
		$("#select2-carNumberSelect2-container").prepend(str);
		if (row.initTime) {

			this.startTime = row.initStartTime;
			this.endTime = row.initEndTime;
			$('#datetimepicker1').val(this.startTime);
			$('#datetimepicker3').val(this.startTime);
			$('#datetimepicker2').val(this.endTime);
			$('#datetimepicker4').val(this.endTime);
		}


		this.companySelected(row)
		// 调用数据绘图的接口
		this.showCheart()
	}

	/**
	 * 待维修的删除
	 */
	deleteRepaireRow(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			var reqdata = "id=" + row.id;
			this.jsonApiService.http('deviceRepaired/delDeviceRepairedById.html', reqdata).subscribe(result => {
				this.jsonApiService.message(result.message);
				this.getTabData('4_1');
			})
		})
	}
}
